Does the Reading Time module work when used in a posts query loop? I added it, and it just shows the same reading time on all posts, which doesn’t match the reading time when it’s placed on the post single template itself.
I assume the module just doesn’t work in loops, but it would be very handy if it did since the reading time could then be in the meta of the listing archive page.
The reading time element calculates the reading time from the content on the page. So when using a query loop the element doesn’t have access to the post’s content. I think this is more of a feature request than a bug though.
I don’t know if it was meant to work on loops or not, if so, then it’s a bug.
The code can certainly access the main content and count it, that’s not impossible or anything although it could be a performance drag if the count is not cached with posts or something.
In any case, I was hoping to not have to use a separate plugin for this and got excited only to see it doesn’t work in a loop so now I’m still stuck using a counting plugin anyway.
I’m not sure if this is good or bad; I’m not very familiar with PHP.
but this code works for me. Put this inside the code block.
<?php
// Function to calculate reading time
if (!function_exists('calculate_reading_time_wp')) {
// Function to calculate reading time
function calculate_reading_time_wp($post_id) {
// Get post content by post ID
$post_content = get_post_field('post_content', $post_id);
// Calculate number of words
$word_count = str_word_count(strip_tags($post_content));
// Average reading speed (words per minute)
$average_reading_speed = 200;
// Calculate reading time (in minutes)
$reading_time = ceil($word_count / $average_reading_speed);
return $reading_time;
}
}
// Example usage:
// Get the ID of the current post
$post_id = get_the_ID();
// Calculate reading time for the current post
$reading_time = calculate_reading_time_wp($post_id);
// Output reading time
echo 'Lecture ' . $reading_time . ' minutes';
?>