我在single.php
文件内的Wordpress主题中添加了下一个和上一个帖子的缩略图。
它可以按要求工作,但显示通知:
注意::尝试在第27行的\ wp-content \ themes \ theme \ template-parts \ content-footer.php中获取非对象的属性
我已经尝试了一些本网站类似答案中的示例,但它们对我不起作用。
我同时删除了$prevPost->ID
和$nextPost->ID
,但随后显示了当前帖子的缩略图。
导致错误的代码如下: 引起通知的代码行在下面的第三和第四行:
<?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) );
?>
使用以下代码调用缩略图:
<div class="uk-width-auto"><?php echo $prevthumbnail; ?></div>
和<div class="uk-width-auto"><?php echo $nextthumbnail; ?></div>
都可以。
该错误仅是一个通知,因此除非启用了wordpress调试,否则它不会破坏网站,甚至不会出现该错误。但是,我希望不要收到此通知,以免引起客户的关注。
关于如何解决此问题的任何想法?
答案 0 :(得分:2)
因此,在WordPress中-数据库中的第一篇文章将不会有“上一个”帖子,而最后一篇文章将不会具有“下一个”帖子-因此,这种行为是完全正常的。
为防止通知,您只需要检查它是否首先存在-我通常喜欢使用empty进行检查-像这样:
$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) );
}
请注意,将$nextthumbnail
和/或$prevthumbnail
保留为未定义变量可能会产生不良影响,因此,为了解决这个问题,我建议进一步修改代码:
$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) );