I am trying to code a function for Wordpress Post navigation but i am getting
Trying to get property of non object
error in lines with $prevpost->ID
and $nextpost->ID
, the code is this:
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;
Making a var_dump($prevpost) outputs this:
string(0) ""
You may try something like following, because $prevpost
and $nextpost
could return empty/null
if there is no matching posts are available.
$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) );
}
Read more on Codex
about get_previous_post and get_next_post to know how they work and what they return on any condition.
Update: Check the function's arguments, you have used (in both previous and next):
previous_post_link( $format, $link, $in_same_cat = false, $excluded_terms = '', $taxonomy = 'category' );
You should use:
previous_post_link( '%link', _x( '<i class="icon-chevron-left"></i><span class="mm-prev-post-title">%title</span>', FALSE, 'mm-cube' ) );
Use same order for other function. Check more on Codex about previous_post_link and next_post_link