Automatically create pages in a post based on number of words

This is tough to do programmatically because of potential variations in html and how the tags balance. However, if you were to try, here’s how I’d suggest doing it.

First of all, WordPress sets up the post pagination in setup_postdata(), which is called at the end of the_post(). That means you need to get those <!--nextpage--> lines in the posts before the end of the_post(). The 'loop_start' action should work for those purposes. It even passes a copy of the current WP_Query object by reference, so you can make changes directly to the queried posts!

Something like this is a start:

add_action( 'loop_start', 'wpse14677_loop_start' );

function wpse14677_loop_start( $query ) {
    foreach( $query->posts as $index => $post ) {
        $words = preg_split( '/ +/', $post->post_content, PREG_SPLIT_NO_EMPTY );
        $pages = array();
        while ( $words ) {
            $word_count = count ( $words );
            if ( 200 >= $word_count ) {
                $pages[] = implode( ' ', $words );
                $words = array();
            } else {
                $pages[] = implode( ' ', array_slice( $words, 0, 200 ) );
                $words = array_slice( $words, 200 );
            }
        }
        $page_count = count( $pages );
        if( 1 < $page_count ) {
            $query->posts[ $index ]->post_content = implode( "\n<!--nextpage-->\n", $pages );
        }
    }
}

Hopefully that gives you an idea of what you would need to do. I’d suggest finding some way of temporarily stripping html tags and replacing them after inserting the nextpage flags, because the function above will also count spaces inside HTML tags, and could even put a page break inside one.

Leave a Comment