Assign Random Featured Images To All Posts

·

, ,

Could be used for setting up dummy content for a staging environment, or something similar. Be my guest and let me know how you decide to use it in the comments! Also, check my github for this function built into a WP-CLI command.

[code language=”php”]
$posts = new WP_Query( array(
‘posts_per_page’ => -1,
‘post_type’ => ‘post’,
));

$post_ids = array();

while ( $posts->have_posts() ) {
$posts->the_post();
array_push( $post_ids, get_the_ID() );
}

wp_reset_query();

$attachments = new WP_Query( array(
‘posts_per_page’ => -1,
‘post_type’ => ‘attachment’,
‘post_status’ => ‘inherit’,
));

$attachment_ids = array();

while ( $attachments->have_posts() ) {
$attachments->the_post();
array_push( $attachment_ids, get_the_ID() );
}

wp_reset_query();

foreach ( $post_ids as $post_id ) {
$attachment_id = rand( 0, count( $attachment_ids ) – 1 );

echo ‘post:’ . $post_id . ‘ attachment:’ . $attachment_ids[$attachment_id];

if ( update_post_meta( $post_id, ‘_thumbnail_id’, $attachment_ids[$attachment_id] ) )
echo ‘ SUCCESS’;
else
echo ‘ FAILED’;
}

die( ‘script complete’ );[/code]

4 responses to “Assign Random Featured Images To All Posts”

  1. Thanks for the script, seems pretty solid. But, can you help a noob out and maybe explain where to run this script in order to actually set random featured images to posts?

    1. federicojacobi Avatar

      upload a bunch of image to your Media Library.

      copy+paste the code in your functions.php at the very end. Then open a page in your browser. You’ll see a bunch of message saying it went ok, then ERASE all the code you put in functions.php.

      Note this is a quick and dirty way of making this work. There is better approaches, but none faster.

  2. Thanks for the script, seems pretty solid. But, can you help a noob out and maybe explain where to run this script in order to actually set random featured images to posts?

    1. federicojacobi Avatar

      upload a bunch of image to your Media Library.

      copy+paste the code in your functions.php at the very end. Then open a page in your browser. You’ll see a bunch of message saying it went ok, then ERASE all the code you put in functions.php.

      Note this is a quick and dirty way of making this work. There is better approaches, but none faster.

Leave a Reply to federicojacobiCancel reply

Discover more from Rich Collier

Subscribe now to keep reading and get access to the full archive.

Continue reading