Hello,
for calculating the reading time of a post i need to count the words.
posts will created with severals fieldsets in a flexible content field. So i have to loop the row layouts, pick the differents fields with texts where the words should count and merge all together to get the total number of words.
that’s what i did so far:
if ( have_rows( 'module_post') ):
while ( have_rows( 'module_post') ) : the_row();
if ( get_row_layout() == 'module_text' ) : // Text
$content = get_sub_field( 'module_post' );
$word_count = str_word_count( strip_tags( $content ) );
return $word_count;
elseif ( get_row_layout() == 'module_intro' ) : // Intro
[...]
endif;
endwhile;
endif; //module_post
As result i have from every sub_field(‘module_post’) the word count. Now i have to merge the differents word counts and add the word count from other fields in other row layouts.
Can someone give me please an advice how to do it?
Many thanks in advance!
Found a solution for me with array_push:
if ( have_rows( 'module_post') ):
$stackWords = array();
while ( have_rows( 'module_post') ) : the_row();
if ( get_row_layout() == 'module_text' ) : // Text
$content = get_sub_field( 'module_post' );
array_push($stackWords, $content);
endif;
endwhile;
$words = implode( ", ", $stackWords );
$word_count = str_word_count( strip_tags( $words ) );
//$readingtime = ceil($word_count / 200);
//echo $word_count;
endif; //module_post
If there a better solution, let me know. thank you!