Last active
September 5, 2024 01:43
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Does this get added to the functions.php file or somewhere else?