如何在上一篇文章缩略图中修复“试图获取非对象的属性”通知
I added a thumbnail for next and previous post in my Wordpress theme specifically inside the single.php
file.
It works as require but it is displaying the notice:
Notice: Trying to get property of non-object in \wp-content\themes\theme\template-parts\content-footer.php on line 27
I have tried out some of the examples from similar answers in this website but they do not work for me.
I removed both $prevPost->ID
and $nextPost->ID
but it then displays the current post thumbnail instead.
The code causing the error is below: The line of code causing the notice is the 3rd and 4th lines below:
<?php
$prevPost = get_previous_post();
$nextPost = get_next_post();
$prevthumbnail = get_the_post_thumbnail($prevPost->ID, array(50,50) );
$nextthumbnail = get_the_post_thumbnail($nextPost->ID, array(50,50) );
?>
The thumbnails were called using the codes below:
<div class="uk-width-auto"><?php echo $prevthumbnail; ?></div>
and <div class="uk-width-auto"><?php echo $nextthumbnail; ?></div>
which both works.
The error is just a notice so it does not break the website or even appear unless wordpress debug is enabled. However, I would prefer not getting this notice so as not to cause some concern for my client.
Any idea on how to resolve this?
So, in WordPress - the first post in the database is NOT going to have a "previous" post, and the last post is not going to have a "next" - so this behavior is perfectly normal.
To prevent the notice, you just need to check if it exists first - I typically like to use empty to perform the check - like so:
$prevPost = get_previous_post();
$nextPost = get_next_post();
if ( ! empty( $prevPost->ID ) ) {
$prevthumbnail = get_the_post_thumbnail($prevPost->ID, array(50,50) );
}
if ( ! empty( $nextPost->ID ) ) {
$nextthumbnail = get_the_post_thumbnail($nextPost->ID, array(50,50) );
}
Note that this may have the undesirable effect of leaving $nextthumbnail
and / or $prevthumbnail
as undefined variables, so to combat that, I'd recommend modifying the code even further:
$prevPost = get_previous_post();
$nextPost = get_next_post();
// use a ternary to set the thumbnail if not empty, or empty string if empty
$prevthumbnail = ( empty( $prevPost->ID ) ) ? '' : get_the_post_thumbnail($prevPost->ID, array(50,50) );
// use a ternary to set the thumbnail if not empty, or empty string if empty
$nextthumbnail = ( empty( $nextPost->ID ) ) ? '' : get_the_post_thumbnail($nextPost->ID, array(50,50) );