I've got a template part in a custom theme and all I'm doing is a WordPress query and in the loop displaying the post thumbnail.
<?php $posts = $args['posts'];
$q_args = [
'post_type' => 'post',
'post__in' => $posts
];
$posts_query = new WP_Query($q_args);
if( $posts_query->have_posts() ) { ?>
<div >
<?php while( $posts_query->have_posts() ) {
$posts_query->the_post();
$post_id = get_the_ID(); ?>
<div >
<a href="<?php the_permalink(); ?>">
<div >
<?= get_the_post_thumbnail($post_id, 'blog-thumbnail') ?>
<?= get_the_date('d M Y'); ?>
<?php the_title('<h3>', '</h3>'); ?>
</div>
</a>
</div>
<?php }
wp_reset_postdata(); ?>
</div>
<?php } ?>
When I go to view the page the loop shows, and everything pulls through correctly, however I get an alert before the thumbnail image
Warning: Attempt to read property "ID" on int in /wp-includes/post-thumbnail-template.php on line 116
Looking at line 116 in that file it's part of the update_post_thumbnail_cache function
function update_post_thumbnail_cache( $wp_query = null ) {
if ( ! $wp_query ) {
$wp_query = $GLOBALS['wp_query'];
}
if ( $wp_query->thumbnails_cached ) {
return;
}
$thumb_ids = array();
foreach ( $wp_query->posts as $post ) {
$id = get_post_thumbnail_id( $post->ID );
if ( $id ) {
$thumb_ids[] = $id;
}
}
if ( ! empty( $thumb_ids ) ) {
_prime_post_caches( $thumb_ids, false, true );
}
$wp_query->thumbnails_cached = true;
}
I thought at first it was that because I was passing the post ID to get_the_post_thumbnail, but if I change that to passing the post object I still get the same warning. Can anyone share with me what I've done to cause this warning?
Thanks!
CodePudding user response:
After a lot of head scratching around this I ended up going in a different direction. Instead of using get_the_post_thumbnail() I opted to get the ID of the post thumbnail ( using get_post_thumbnail_id() ) and then using wp_get_attachment_image() to output it and this removed the error.
<?php $posts = $args['posts'];
$q_args = [
'post_type' => 'post',
'post__in' => $posts
];
$posts_query = new WP_Query($q_args);
if( $posts_query->have_posts() ) { ?>
<div >
<?php while( $posts_query->have_posts() ) {
$posts_query->the_post();
$thumbnail_id = get_post_thumbnail_id (); ?>
<div >
<a href="<?php the_permalink(); ?>">
<div >
<?= wp_get_attachment_image($thumbnail_id, 'blog-thumbnail') ?>
<?= get_the_date('d M Y'); ?>
<?php the_title('<h3>', '</h3>'); ?>
</div>
</a>
</div>
<?php }
wp_reset_postdata(); ?>
</div>
<?php } ?>
This isn't the most optimal solution as you are creating extra database calls running get_post_thumbnail_id and wp_get_attachment_image but it works.