Wordpress

Auto set featured image for post by random

By 0 Comments

When you want to set thumbnail for every post by random, you can do the following

a. Upload your photos on the site by “Admin Dashboard > Media > Upload”

b. Get the ID of the first and last photo.
For example, you upload 10 photos,
Begin_ID: 1
End_ID: 10

c. Copy and paste the code below into your functions.php
Change the value of the variable Begin_ID and End_ID by your value

d. Click F5 to refresh!

$begin_ID = 1;
$end_ID = 10;
 
$items = array();
 
for ($i = $begin_ID; $i <= $end_ID; $i++) {
    $items[] = $i;
}
 
$posts = new WP_Query(array(
    'post_type' => array('post'),
    'posts_per_page' => -1
));
 
$index = 0;
 
while ($posts->have_posts()){
    $posts->the_post();
    set_post_thumbnail(get_the_ID(), $items[$index]);
    if ($index == count($items) - 1)
        $index = 0;
    else
        $index++;
}
 
wp_reset_postdata();