WordPress Post reading time without plugin

2022-11-17T17:50:58.000000Z byAdmin inWordPress
WordPress Post reading time without plugin

For Post: Go to wp-content/your-theme/functions.php file and scroll all the way down.

Insert this hook:


/*Post Reading Time count */
if (!function_exists('your_function_name_reading_time')) :
function your_function_name_reading_time($post_id)
{
$content = apply_filters('the_content', get_post_field('post_content', $post_id));
$read_words = esc_attr(get_theme_mod('global_show_min_read_number', '10'));
$decode_content = html_entity_decode($content);
$filter_shortcode = do_shortcode($decode_content);
$strip_tags = wp_strip_all_tags($filter_shortcode, true);
$count = str_word_count($strip_tags);
$word_per_min = (absint($count) / $read_words);
$word_per_min = ceil($word_per_min);
if (absint($word_per_min) > 0) {
$word_count_strings = sprintf(_n(
'%s min ',
'%s min ',
number_format_i18n($word_per_min),
'isha'
), number_format_i18n($word_per_min));
if ('post' == get_post_type($post_id)) :
echo esc_html($word_count_strings);
endif;
}
if (absint($word_per_min) == Null) {
echo '1 min';
}
}
endif;

Use this function anywhere in your template:

<?php your_function_name_reading_time( get_the_ID() ); ?>