Reputation: 1175
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.
Upvotes: 1
Views: 68
Reputation: 26055
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 );
}
}
Upvotes: 1