2

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>';
        }

    }

}
  • How's your loop? Does it contain a call to the_post() ? Does it work on the default theme? – birgire Apr 30 '15 at 14:11
  • @birgire The function is called outside of the loop. Here is the complete single.php on Pastebin – Simon Bouchard Apr 30 '15 at 14:43
1

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.

2

$multipage is an "inside the Loop" variable. I did not track down exactly where and how it is set but given that information alone the obvious solution is to put your code inside a Loop, which is good practice anyway as a number of things depend upon that Loop. Something like:

if (have_posts()) {
    while (have_posts() {
      the_post();
      $sbwp_story_thumbnail = "";
      // ....
    }
}
  • Thank you sir, I have resolved this issue. My function needed to placed inside the loop as you said. – Simon Bouchard Apr 30 '15 at 15:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.