试图获得非对象的属性

时间:2014-04-09 17:04:31

标签: php wordpress

我正在尝试为Wordpress Post导航编写一个函数,但我正在

  

尝试获取非对象的属性

$prevpost->ID$nextpost->ID行中的

错误,代码为:

if ( ! function_exists( 'mm_post_nav' ) ) :
/**
 * Displays navigation to next/previous post when applicable.
 *
 * @since 1.0
 *
 * @return void
  */
function mm_post_nav() {
global $post;

// Don't print empty markup if there's nowhere to navigate.
$previous = ( is_attachment() ) ? get_post( $post->post_parent ) : get_adjacent_post( false, '', true );
$next     = get_adjacent_post( false, '', false );
$prevpost = get_previous_post(true);
$prevThumbnail = get_the_post_thumbnail($prevpost->ID, array(44,44) );
$nextpost = get_next_post(true);
$nextThumbnail = get_the_post_thumbnail($nextpost->ID, array(44,44) );
if ( ! $next && ! $previous )
    return;
?>
<nav class="mm-post-nav" role="navigation">
    <h1 class="screen-reader-text"><?php _e( 'Post navigation', 'mm-cube' ); ?></h1>
    <div class="mm-single-nav">
        <div class="mm-prev-link">

            <?php previous_post_link( '%link', _x( '<i class="icon-chevron-left"></i><span class="mm-prev-post-title"> %title</span>', 'Previous post link', 'mm-cube' ) ); ?>
        </div>
        <div class="mm-next-link">

            <?php next_post_link( '%link', _x( '<span class="mm-next-post-title">%title</span><i class="icon-chevron-right"></i>' , 'Next post link', 'mm-cube' ) ); ?>

        </div>
    </div><!-- .nav-links -->
    <div class="clear"></div>
</nav><!-- .navigation -->
<?php
}
endif;

制作var_dump($ prevpost)输出:

string(0) ""

1 个答案:

答案 0 :(得分:3)

您可以尝试以下内容,因为$prevpost$nextpost如果没有匹配的帖子可以返回empty/null

$prevpost = get_previous_post(true);
if (!empty( $prevpost )) {
    $prevThumbnail = get_the_post_thumbnail($prevpost->ID, array(44,44) );
}
$nextpost = get_next_post(true);
if (!empty( $nextpost )) {
    $nextThumbnail = get_the_post_thumbnail($nextpost->ID, array(44,44) );
}

返回值(get_previous_post和get_next_post)

  • 如果成功发布对象。
  • 如果未设置全局$ post,则为空。
  • 如果不存在相应的帖子,则为空字符串。

了解Codex关于get_previous_postget_next_post的更多信息,了解它们的工作原理以及它们在任何条件下的返回情况。

更新:检查您使用过的函数的参数(前一个和下一个):

previous_post_link( $format, $link, $in_same_cat = false, $excluded_terms = '', $taxonomy = 'category' );

您应该使用:

previous_post_link( '%link', _x( '<i class="icon-chevron-left"></i><span class="mm-prev-post-title">%title</span>', FALSE, 'mm-cube' ) );

对其他功能使用相同的顺序。有关previous_post_linknext_post_link

的详情,请参阅Codex