Search code examples
wordpressnavigationposts

Wordpress get_prev & get_next not working


I can't understand why my code is not working:

<?php 
function get_prev_next_links(){
    echo '<div class="post-nav">';
    $prev_post = get_previous_post();
    if ( !empty( $prev_post ) );
    echo '<div class="prev-post">';
    echo '<a href="'get_permalink( $prev_post->ID )'">&lsaquo; Previous ('echo $prev_post->post_title')</a>';
    echo '</div>';
    endif;

    $next_post = get_next_post();

    if ( !empty( $next_post ) );
    echo '<div class="next-post">';
    echo '<a href="'get_permalink( $next_post->ID )'">Next ('echo $next_post->post_title') &rsaquo;</a>';
    echo '</div>';
    endif;

    echo '</div>';
}
add_shortcode ( 'the_prev_next_links' , 'get_prev_next_links' );
?>

I pasted this code into my functions.php file, so that I can use the shortcode [the_prev_next_links] to call the function. But it just gives me the 'whitescreen'. So there must be something missing in my above code, or something that I've got wrong.

Note: this is outside the loop.

Any pointers?
Thanks :-)


Solution

  • Your problem is probably in your if syntax. You're ending the if statements with semicolons like this:

    if ( !empty( $next_post ) );
    

    The should have colons, like this:

    if ( !empty( $next_post ) ):
    

    Here's the PHP reference on the "alternate syntax" for control structures: http://php.net/manual/en/control-structures.alternative-syntax.php

    Personally, I prefer to use braces to wrap code blocks, but this is valid too. Most editors will highlight brace pairs, which can help while editing and debugging.

    You also need to concatenate your strings properly. This is incorrect:

    echo '<a href="'get_permalink( $prev_post->ID )'">&lsaquo; Previous ('echo $prev_post->post_title')</a>';
    

    This will work:

    echo '<a href="' . get_permalink( $prev_post->ID ) . '">&lsaquo; Previous (' . $prev_post->post_title . ')</a>';