简体   繁体   中英

Wordpress looping through posts setting thumbnail

I am trying to loop through all posts in Wordpress and set a thumbnail image if the post doesn't have one. I am using the following code in the functions file:

$args = array('post_type' => 'posts');
$loop = new WP_Query($args);

while ($loop->have_posts()):
    $loop->the_post();
    $attach_id = '13057';

    if (has_post_thumbnail())
    {
        // check if the post has a Post Thumbnail assigned to it.
    }
    else
    {     
        add_post_meta($loop->ID, '_thumbnail_id', $attach_id); 
    }

endwhile;

It doesn't seem to be working though its just having no effect on the posts whatsoever, I would really appreciate your input, many thanks in advance.

I'm really not sure what's wrong with your code, but maybe this can clarify things: When should you use WP_Query vs query_posts() vs get_posts()? .

Using get_posts() works for me:

$args = array(
    'numberposts' => -1,
    'post_type'   => 'post',
    'post_status' => array('publish','future','draft')
);
$get = get_posts( $args );
if( $get )
{
    $attach_id = 661; // Valid attachment ID in my system
    foreach( $get as $post )
    {
        if ( !has_post_thumbnail( $post->ID ) )
            add_post_meta( $post->ID, '_thumbnail_id', $attach_id ); 
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM