I'm trying to split a post in pages at every 200 characters with <!--nextpage-->

I found this code on this page that actually looks pretty good (for my understanding alone - yes I'm a newbie to development):

$content = get_the_content();
$strings = wordwrap($content, 500, "<!--break-->"); //insert this every 500 chars, but preserve whole words.
$chunks = explode("<!--break-->", $strings); create a new string of 500-char sections.

ob_start(); // buffer the output of the following expressions...
foreach($chunks as $chunk_content) {
    echo '<span>'; // use <span> instead of <div> so as to not interrupt the paragraph formatting of the content when viewed normally (graceful degradation).
    echo $chunk_content;
    echo '</span> ';
$segmented_content = ob_get_contents(); // put the results of the above expressions into a variable.
ob_end_clean(); // discard the expressions that were buffered.
echo nl2br($segmented_content); // put the result through a filter which replaces line-breaks with <br> tags.

I tried to replace <!--break--> by <!--nextpage-->, it looks like <!--nextpage--> is not recognized as such in html!

How can it work?

(Yes i've tried a lot of code functions and plugins... I've already inserted wp_link_pages(); still none would work :/ )

Thanks for any help...

  • What if after 200 chars you are positioned within an <img alt=""> tag? Splitting that img tag, could bring down the site's layout. – birgire Sep 22 '15 at 13:49
  • You could try to grab the closing </p> tags, but then we should also watch out for nested tags. Maybe a clever usage of DomDocument could help us determine where we are positioned in the DOM tree? This might of course get easier if this would be pure text (no HTML). Don't know if my answer here would be of any help? – birgire Sep 22 '15 at 17:40

Your Answer

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

Browse other questions tagged or ask your own question.