• Resolved TatsujinUK

    (@tatsujinuk)


    OK, we have this code to display next and previous articles in the sidebar on a website we are working on:

    <h3><?php _e('Next Article') ?></h3>
    <p><?php next_post_link('<p>%link</p>'); ?></p>
    <h3><?php _e('Previous Article') ?></h3>
    <p><?php previous_post_link('<p>%link</p>'); ?></p>

    What we need to do is alter this so that “if” there is a Next Article, it shows the h3 and p, “else” it should display nothing at all . . . same with the Previous Article.

    Any ideas? Thanks in advance! 🙂

Viewing 5 replies - 1 through 5 (of 5 total)
  • previous_post_link() and next_post_link() output the link. You need to get the link first instead. Here’s how I’d go about it:

    <?php // Let's only attempt this on posts.
    if ( is_singular( 'post' ) ) {
        if ( $next_post_link = get_next_post_link( '<p>%link</p>' ) ) {
            echo '<h3>' . __( 'Next Article' ) . '</h3>';
            echo $next_post_link;
        }
    
        if ( $previous_post_link = get_previous_post_link( '<p>%link</p>' ) ) {
            echo '<h3>' . __( 'Previous Article' ) . '</h3>';
            echo $previous_post_link;
        }
    } ?>
    Moderator Samuel Wood (Otto)

    (@otto42)

    ww.wp.xz.cn Admin

    The next post link and previous post link functions only display something if there is something to display. So move the h3 and everything else into those function calls.

    <?php next_post_link('<h3>'.__('Next Article').'</h3><p>%link</p>'); ?>
    <?php previous_post_link('<h3>'.__('Previous Article').'</h3><p>%link</p>'); ?>
    Thread Starter TatsujinUK

    (@tatsujinuk)

    Thanks Nathan, but it just comes up as blank when I try that . . .

    Where are you attempting to place this code? Are you viewing an actual post (not a custom post type but a regular post)?

    I thought there could be an error in the code since I wrote it on the fly but I’ve tested it myself and it works perfectly so the issue will be down to implementation.

    Thread Starter TatsujinUK

    (@tatsujinuk)

    Samuel > thank you, that’s cracked it and does just what I need it to do.

    Nathan > it’s being added directly into a page/post template php file.

Viewing 5 replies - 1 through 5 (of 5 total)

The topic ‘Help with "IF / ELSE"’ is closed to new replies.