Reading Time Variable for Rank Math
Adds a %wpide_reading_time% variable to Rank Math, so titles, descriptions and social text can include an estimated reading time.
Opens WPIDE on
Code
// Average reading speed.
$wpide_rm_wpm = 220;
add_action( 'rank_math/vars/register_extra_replacements', function () use ( $wpide_rm_wpm ) {
if ( ! function_exists( 'rank_math_register_var_replacement' ) ) {
return;
}
rank_math_register_var_replacement(
'wpide_reading_time',
array(
'name' => 'Reading time',
'description' => 'Estimated reading time of the post',
'variable' => 'wpide_reading_time',
'example' => '4 min read',
),
function () use ( $wpide_rm_wpm ) {
$post = get_post();
if ( ! $post ) {
return '';
}
$words = str_word_count( wp_strip_all_tags( strip_shortcodes( $post->post_content ) ) );
return sprintf( '%d min read', max( 1, (int) ceil( $words / max( 1, $wpide_rm_wpm ) ) ) );
}
);
} );
Notes
Type %wpide_reading_time% in any Rank Math title or description field.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.