Stylize pagination links in WordPress posts

WordPress offers a relatively little known feature to split your extremely long posts into different pages. However, it’s a bit difficult to stylize so it matches your overall site style since by default, WordPress doesn’t apply CSS classes to target its elements. Let’s learn how to filter the function that outputs them and add classes to stylize them.

Overview

Posts can be paginated by typing the <!--nextpage--> Quicktag while writing the post content, to indicate that the content following the tag must be placed in a new page. The links are then generated using the function wp_link_pages, that creates the post content pagination.

While you must considerate the SEO implications of paginating content, and that’s an entire topic on its own, you probably have a good reason to do so, such as an incredibly long article, probably with a lot of images and embedded videos that would take too much to load and would consume many resources on your server.

Initialization

We can call the wp_link_pages function in our WordPress theme including our CSS classes ready to be styled like this:

<?php
    wp_link_pages(
        'before' => '<div class="nextpages">' . esc_html__( 'Next Pages:', 'startfunction' ),
        'after' => '</div>',
        'pagelink' => '<span class="pagelink">%</span>'
    );

Filtering

What happens if we’re using a child theme? if it’s properly built using get_template_part we could copy the file to our child theme and reinitialize the function with the proper values.

A good alternative would be to use the filter wp_link_pages_args to override the initialization of the wp_link_pages function. We can add the following code in the functions.php file of our child theme:

<?php
function startfunction_link_pages( $r ) {
    $args = array(
        'before' => '<div class="nextpages">' . esc_html__( 'Next Pages:', 'startfunction' ),
        'after' => '</div>',
        'pagelink' => '<span class="pagelink">%</span>'
    );
    return wp_parse_args( $args, $r );

    }
add_filter( 'wp_link_pages_args','startfunction_link_pages' );

This is also a good alternative if the function is initialized inside a framework and we want to override the values for our own purpose.

Leave a Reply