WordPress post/page pagination (page links) to go back to the first section

If we want to add a First page link between Previous page and Next page links:

Pages: Previous page First page Next page

then we could use the wp_link_pages_args, wp_link_pages and wp_link_pages_link filters.

Here’s one such example:

Example

First we check the next_or_number attribute to see if the next mode is active:

add_filter( 'wp_link_pages_args', 'wpse_initialize' );

function wpse_initialize( Array $args )
{   
    // Run only once
    remove_filter( current_filter(), __FUNCTION__ );

    // Activate only for 'next'
    if( 'next' === $args['next_or_number'] )
        add_filter( 'wp_link_pages_link', 'wpse_add_first_page_link', 10, 2 );

    return $args;
} 

If it’s active then we add the following filter callback to the wp_link_pages_link filter:

function wpse_add_first_page_link( $link, $nextorprev ) 
{
    // Custom logic for the "First page" part
    if( $nextorprev <= get_query_var( 'page', 1 ) )
        $link .= sprintf(
            ' %s%s%s%s</a> ',
            _wp_link_page( 1 ),
            $r['link_before'],
            esc_html__( 'First Page', 'mydomain' ),
            $r['link_after']
        );

    return $link;
}

Here we use the _wp_link_page() function that’s used within the wp_link_pages() function.

This should display the First page part.

Finally some house cleaning:

add_filter( 'wp_link_pages', 'wpse_finalize' );

function wpse_finalize( $html )
{    
    // Run only once
    remove_filter( current_filter(), __FUNCTION__ );

    // Remove our previous filter callback
    remove_filter( 'wp_link_pages_link', 'wpse_add_first_page_link', 10 );

    return $html;
} 

Hope you can adjust this to your needs.

Leave a Comment