Getting content from a single *page* of a post

What function can I use to fetch content of a single page within a post?
Let’s say I want to split my post into 5 pages – how can I get content of, say, page 3?

Can’t seem to find this in Codex…

Related posts

Leave a Reply

2 comments

  1. This should do the trick:

    /**
     * For posts paginated using <!--nextpage-->, return a particular "page" of content.
     * This function uses code from WP's setup_postdata() function.
     * @param string $content the content to search for paginated page content.
     * @param int $page_number the index of the page to return the content for.
     */
    function get_nextpage_content( $content, $page_number ) {
        if ( strpos( $content, '<!--nextpage-->' ) ) {
            $content = str_replace("n<!--nextpage-->n", '<!--nextpage-->', $content);
            $content = str_replace("n<!--nextpage-->", '<!--nextpage-->', $content);
            $content = str_replace("<!--nextpage-->n", '<!--nextpage-->', $content);
            $pages = explode('<!--nextpage-->', $content);
            return ( isset ( $pages[$page_number - 1] ) ) ? $pages[$page_number - 1] : false;
        } else {
            return false;
        }
    }
    

    Usage:

    // Get the second page of content with a paginated post
    echo apply_filters( 'the_content', get_nextpage_content( $post->post_content, 2 ) );
    
  2. You should first explode the content, and then perform a few functions on the content to enable WordPress’ “Auto paragraph” formatting and Shortcodes.

    $post_content = $wpdb->get_var("SELECT post_content FROM $wpdb->posts WHERE ID = {$post->ID} LIMIT 0,1");
    $raw_pages = explode('<!--nextpage-->', $post_content);
    foreach($raw_pages as $raw_page){
        $pages[] = wpautop( do_shortcode( trim($main_content) ) );
    }
    

    Now you can echo each page like so:

    <?php echo $page[0]; // Page 1 ?>
    

    You can also implement this feature/concept a tad differently. I like to split my post into two pages to give my copywriter the ability to create the main content and sidebar content. I basically assign the second page to the sidebar. While you could use the same code as above, a cleaner (yet less flexible way) might be to do something like this…

    $post_content = $wpdb->get_var("SELECT post_content FROM $wpdb->posts WHERE ID = {$post->ID} LIMIT 0,1");
    list($main_content, $sidebar_content) = explode('<!--nextpage-->', $post_content);
    $main_content = wpautop( do_shortcode( trim($main_content) ) );
    $sidebar_content = wpautop( do_shortcode( trim($sidebar_content ) ) );
    

    Now I can just echo out either the $main_content or $sidebar_content variable wherever I want in my page template.