WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Basically every time that I publish a post I want that a random image from my wordpress database be set as the feature image for that post. Can someone help me with this please!

share|improve this question
up vote 1 down vote accepted

Here is a way:

// listen for post being published
add_action('publish_post', 'dreis_random_featured_image');

function dreis_random_featured_image() {
    global $post;

    // find one random image    
    $args = array(
        'post_type' => 'attachment',
        'post_mime_type' => 'image',
        'post_status' => 'inherit',
        'posts_per_page' => 1,
        'orderby' => 'rand'

    $random_image = new WP_Query($args);

    foreach($random_image as $image){
        // set as thumbnail
        set_post_thumbnail($post->ID, $image->ID);

    // reset loop to avoid weirdness
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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