我在Wordpress主题中专门为single.php
文件内的下一个和上一个帖子添加了缩略图。
它可以按要求运行,但显示通知:
注意:试图在第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调试,否则它不会破坏网站,甚至不会出现该错误。但是,我希望不要收到此通知,以免引起客户的关注。
关于如何解决这个问题的任何想法?
因此,在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) );
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句