the_content and wp_link_pages

The question:

Many plugins seem to be adding a filter/action hook to the_content to display related posts, advertisements and such. The problem is I these appear before the post pagination so it the pagination is pushed down below.

Is it possible to display the post pagination right after the content? It appears wp_link_pages can only be used inside the loop.

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

I guess you have:

the_content();
wp_link_pages();

in your theme file. So you can instead try the following (PHP 5.4+):

/**
 * Append the wp_link_pages to the content.
 */
! is_admin() && add_filter( 'the_content', function( $content )
{
    if( in_the_loop() ) 
    {
        $args = [ 'echo' => false ];        // <-- Adjust the arguments to your needs!
        $content .= wp_link_pages( $args );
    }
    return $content;
}, 10 );                                    // <-- Adjust the priority to your needs!

and then adjust the arguments and priority to your needs. Notice the echo parameter, it’s set to false, because we need to return the output. You then have to remove wp_link_pages() from your (child) theme file.

Update:

If we don’t want to remove the extra wp_link_pages() by hand, we can use the wp_link_pages filter to only display the output, within our the_content filter callback:

/**
 * Append the wp_link_pages to the content.
 */
! is_admin() && add_filter( 'the_content', function( $content )
{
    if( in_the_loop() ) 
    {
        $args = [ 'echo' => false, '_show' => true ];  // <-- Adjust the arguments to your needs!
        $content .= wp_link_pages( $args );
    }
    return $content;
}, 10 );                                              // <-- Adjust the priority to your needs!

/**
 * Only display wp_link_pages() output when the '_show' argument is true.
 */
add_filter( 'wp_link_pages', function( $output, $args )
{
    return ! isset( $args['_show'] ) || ! wp_validate_boolean( $args['_show'] ) ? '' : $output;
}, 10, 2 );

where we’ve introduced the extra _show argument for this purpose.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment