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!

有帮助吗?

解决方案

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
    wp_reset_query();
}
许可以下: CC-BY-SA归因
scroll top