I have 100 existing posts of a custom post type that I need to update their featured images... How would I go about creating a query to randomly update these images from an array of say 20 images from the media library?

Any pointers would be great, thanks!

  • Do you want to add random featured images to post that currently don't have a featured image?
    – Tomás Cot
    Aug 20, 2014 at 20:04
  • Hi Tomas, each post already has a featured image that I'd like to change to a new, randomly selected one.
    – JasonD
    Aug 20, 2014 at 23:50

1 Answer 1


This is pseudo-code answer.

  1. First get the posts you want with get_posts (you can pass the post_type as an argument)
  2. Then get the ID of the images you want to set as thumnbail
  3. Now do a loop and try with a query similar to this one:

    "UPDATE wp_postmeta SET meta_value = $image_id WHERE post_id = $post_id AND meta_key = ''_thumbnail_id''"

NOTE: To get the $image_id from the array of key you could use array_rand. You are gonna need wpdb to run the query.

Read the docs, and ask a question if you have any doubts.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.