I use the Advanced Custom Fields Pro plugin on every site I build in WordPress. I think it is a great tool for creating custom websites. But, if you replace the main WordPress editor (Gutenberg or Classic) with ACF’s Flexible Content then it makes getting a reading time assessment a little tricky. So, here is a little function I wrote in order to calculate the average reading time based upon the content within Advanced Custom Fields Flexible Content.
Working out the reading time
First, place this within your theme or child theme’s functions file. Next, replace ‘flexible_content’ with your own Flexible Content field name.
// Reading time calculator function reading_time($the_post_ID){ $total_word_count = 0; // Establish the total word count // Replace 'flexible_content' with your custom field $all_fields = get_field('flexible_content', $the_post_ID, false); // Get the flexible content meta field name foreach ($all_fields as $field) { // Loop the flexible content fields foreach ($field as $key => $value) { // Loop the fields by $key => $value if ($key === 'acf_fc_layout') { // Make sure we're skipping field names, we only want to read field values continue; } $total_word_count = $total_word_count + str_word_count(strip_tags($value)); } } $readingtime = ceil($total_word_count / 200); if ($readingtime <= 1) { // If the reading time is equal to or less than 1 $timer = " min"; } else { $timer = " mins"; } if ($readingtime == 0) { // if the reading time equals 0 then change it to 1 $totalreadingtime = "1" . $timer . " read"; } else { $totalreadingtime = $readingtime . $timer . " read"; } return $totalreadingtime; }
Display the reading time
To display the reading time within your template files use this snippet.
// Display the reading time // Wrap this in the HTML tag of your liking echo reading_time(get_the_ID());
If you like this post then you might like this one too.
How to create a reading timer from WordPress content