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.
Topic characters split the-content posts Wordpress
Category Web