Divide Post content into separate divs for every 500 characters (or any other character counts)

What is the best method for intercepting the_content of a post (for a single post page) and dividing the_content into sections of 500 characters (or any other number of characters), and then outputting each 500-character section wrapped in its own div container?

I understand that get_the_content() will return the post content as a string that can be stored in a variable. But, being new to PHP, I’m not sure how to go about segmenting the content based on character count. We could get the character count using:

    <?php
      $content = get_the_content();
      echo strlen($content);
    ?>

But that is as far as my knowledge goes.
Can anyone help me out with this challenge?

UPDATE:
With some help from Lukas Kolletzki on stackoverflow I have gotten this far:

    <?php
    $content = get_the_content();
    $chunks = str_split($content, 500);

    //Printing each chunk in a div
    foreach($chunks as $chunk_content) {
        echo "<div>";
        echo $chunk_content;
        echo "</div>";
    }
    ?>

This successfully splits the post content into 500-word sections and wraps each of them into separate containers.

Going even further, Lukas suggested using the wordwrap() and explode() functions to ensure that words weren’t cut in half:

    <?php
    $content = get_the_content();
    $strings = wordwrap($content, 500, "<br />"); //Put a {BREAK} every 500 characters
    $chunks = explode("<br />", $strings); //Put each segment separated by {BREAK} into an array field

    //Printing each chunk in a div
    foreach($chunks as $chunk_content) {
        echo "<div class="post-content">";
        echo $chunk_content;
        echo "</div>";
    }
    ?>

This works quite nicely, but now I am realizing that the normal wordpress

tags are not being output. Is this because get_the_content() outputs only text, without the html?

How can I get the paragraphs back into the post content and still maintain the above functionality?

Thanks again, and please do not mark this as duplicate. It’s a much different question than the excerpt_length filter question… or at least I think so.

3 Answers
3

get_the_content() return what’s in the editor, but wpautop filters and such are attached to the_content (which you don’t need inside your split function – just apply it later manually with

apply_filters( 'the_content', $output );

at the end.

You should as well use strip_shortcodes( get_the_content() ); before splitting it up:

$output = get_the_content();
$output = wp_trim_words( $output, 500 );

You’ll need to loop through it as long as you got content and array_push() to your $output = array();.

Leave a Comment