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 class="posts-grid">
<?php while( $posts_query->have_posts() ) {
$posts_query->the_post();
$post_id = get_the_ID(); ?>
<div class="post-container">
<a class="post" href="<?php the_permalink(); ?>">
<div class="post-content">
<?= 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!
My Answer:
It looks like the issue is with the way you are passing the post ID to the get_the_post_thumbnail function. Instead of passing the post ID directly, you should pass the post object itself.
Try updating this line:
php
= get_the_post_thumbnail($post_id, 'blog-thumbnail') ?>
to this:
php
= get_the_post_thumbnail(get_post($post_id), 'blog-thumbnail') ?>
By passing the post object to the get_the_post_thumbnail function, you should be able to resolve the warning you are seeing.
Rate this post
5 of 5 based on 5870 votesComments