Customize previous_post_link and next_post_link Output

The default markup for previous_post_link and next_post_link can be difficult to style and adjust using CSS alone.

WordPress documentation suggests adding to the above functions to adjust the output, but content adjustments made to the single.php and single templates for custom post types may have conflicts that prevent this output from displaying.

Use a function to customize the output to both links (this will affect the default and custom post type templates).

Original Function:

add_filter( 'previous_post_link', 'filter_single_post_pagination', 10, 4 );
add_filter( 'next_post_link',     'filter_single_post_pagination', 10, 4 );
function filter_single_post_pagination( $output, $format, $link, $post )
{
    $title = get_the_title( $post );
    $url   = get_permalink( $post->ID );
    $text  = 'Read previous';
    $class = 'prev-post';
    $rel   = 'prev';

    if ( 'next_post_link' === current_filter() )
    {
        $text  = 'Read next';
        $class = 'next-post';
        $rel   = 'next';
    }
    return "<div class='$class'>
            <div class='title1'>
                <h5><a href='$url' rel='$rel'>$text</a></h5>
            </div>
            <div class='title2'>
                <h5><a href='$url' rel='$rel'>$title</a></h5>
            </div>
        </div>";
}

Sourced here.

Customizations:

add_filter( 'previous_post_link', 'filter_single_post_pagination', 10, 4 );
add_filter( 'next_post_link',     'filter_single_post_pagination', 10, 4 );
function filter_single_post_pagination( $output, $format, $link, $post ) {

    $title = get_the_title( $post );
    $url   = get_permalink( $post->ID );
    $text  = '<<'; // previous nav arrows
    $class = 'prev-post';
    $rel   = 'prev';

    if ( 'next_post_link' === current_filter() )
    {
        $text  = '>>'; // next nav arrows
        $class = 'next-post';
        $rel   = 'next';
    }
    return "<div class='$class'>
            <span><a href='$url' rel='$rel'>
            <span class='inner'>$text</span> $title</a></span> // include inner class for arrow output to allow for independent style adjustments
        </div>";
}

Leave a Reply

katherine as a flat graphic icon

About Me

I’m an African / Ojibwe First Nations Web Developer living in Winnipeg, Manitoba.

Visit the Tips and Blog to see what I’m working on.