wp_link_pages: display current page number only if has multiple page breaks?

I’m trying to build a function to display the current chapter (page) within the single.php file ONLY if there’s more than one chapter (page break).

This function will output the chapter # within the page header under the title. Then I will customize and use the wp_link_pages at the bottom for the chapter pagination.

Currently, my function doesn’t work, it return nothing and if I remove the the IF statement if ( $multipage ) {} it return “Chapter 0”.

I need advice on this one.

/**
* Get current chapter number
*/
if ( ! function_exists( 'sbwp_get_current_chapter' ) ) {

    function sbwp_get_current_chapter() {

        global $page, $numpages, $multipage, $more;

        if ( $multipage ) {
            echo '<p class="page-link accent">';
            echo esc_html(( '' . __( "Chapter ", "sbwp" ) . '' . $page ));
            echo '</p>';
        }

    }

}

2 Answers
2

The $multipage is constructed inside the setup_postdata() method of WP_Query.
It’s called when you run the_post(). So just as @s_ha_dum explained, you have to make a loop around it:

You can try this:

if( have_posts() )
{ 
    the_post();                      // Make a call to setup_postdata().
    echo sbwp_get_current_chapter(); // Display the current chapter.
    rewind_posts();                  // Rewind back.
}

before your main loop, where you must remember to rewind back.

Leave a Comment