Home Forums ACF PRO Estimated Reading time for ACF Blocks


Estimated Reading time for ACF Blocks

  • Hi. Im trying to create a function I can use in my theme to count the words in acf blocks of type text, textarea, and wysiwyg and return an estimated reading time. No matter what I try I just cant get it, and was hoping that someone that knows acf blocks a little better than me might have an idea what is going on.

    My function:

    function estimated_reading_time($post_id) {
    	// Get the post content
    	$content = get_post_field('post_content', $post_id);
    	// If the post content is empty, return 0
    	if (empty($content)) {
    		return 0;
    	// Get the ACF Gutenberg blocks for the post
    	$blocks = parse_blocks($content);
    	// Debug: Output the blocks for debugging
    	// Initialize the word count
    	$word_count = 0;
    	// Loop through the blocks
    	foreach ($blocks as $block) {
    		// Debug: Output the current block for debugging
    		// Check if the block is a valid ACF Gutenberg block
    		if (isset($block['blockName']) && strpos($block['blockName'], 'acf/') === 0 && isset($block['attrs']['data']['block']['value'])) {
    			$block_fields = $block['attrs']['data']['block']['value'];
    			// Loop through the fields within the block
    			foreach ($block_fields as $field) {
    				if (isset($field['field_type']) && isset($field['value'])) {
    					$field_type = $field['field_type'];
    					// Check if the field is a text, textarea, or wysiwyg field
    					if (in_array($field_type, ['text', 'textarea', 'wysiwyg'])) {
    						$field_value = $field['value'];
    						// Count the number of words in the field value
    						$field_word_count = str_word_count(strip_tags($field_value));
    						// Add the field's word count to the total word count
    						$word_count += $field_word_count;
    	// Debug: Output the final word count for debugging
    	// Calculate the estimated reading time based on average reading speed (200 words per minute)
    	$reading_time = round($word_count / 200);
    	return $reading_time;

    Then to use it in my template file I just do
    Reading Time: <?php echo estimated_reading_time( $postid ); ?>

    (and obviously pass that postid into the function).

    I stuck var dumps into the relevant bits to get some debugging info. But im still stuck. Any ideas what I am doing wrong?

Viewing 1 post (of 1 total)

You must be logged in to reply to this topic.