Skip to content

Instantly share code, notes, and snippets.

@danielbachhuber
Last active December 8, 2017 02:56
Show Gist options
  • Save danielbachhuber/6691084 to your computer and use it in GitHub Desktop.
Save danielbachhuber/6691084 to your computer and use it in GitHub Desktop.
Auto-paginate after 500 words, but respect paragraphs and don't leave page stubs.
<?php
/**
* Auto-paginate after 500 words
*/
add_action( 'loop_start', function( $query ) {
if ( ! is_single() || 'post' != get_post_type() || ! $query->is_main_query() )
return;
$content = $query->posts[0]->post_content;
if ( 900 > str_word_count( $content ) )
return;
if ( false !== stripos( $content, '<!--nextpage-->' )
|| false !== stripos( $content, '<!--nopage-->' ) )
return;
$content = wpautop( $content );
$content_array = str_split( $content );
$word_array = str_word_count( $content, 2 );
$word_count = 0;
$next_page_count = 0;
while ( count( $word_array ) > 900 ) {
$word_array = array_slice( $word_array, 500 + $word_count, null, true );
$word_count = 0;
foreach( $word_array as $i => $word ) {
if ( 'p' != $word ) {
$word_count++;
continue;
}
// Found a '<p>'
if ( '<' == $content_array[$i-1] ) {
$k = $i-2;
}
// Found a '</p>'
else if ( '<' == $content_array[$i-2] ) {
$k = $i+3;
} else {
$word_count++;
continue;
}
$k = $k + ( $next_page_count * 15 );
$next_page_count++;
$content = substr( $content, 0, $k ) . '<!--nextpage-->' . substr( $content, $k );
break;
}
}
$query->posts[0]->post_content = $content;
});
@happygrrrl
Copy link

Does this get added to the functions.php file or somewhere else?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment