Skip to content

Instantly share code, notes, and snippets.

@moxet
Created June 21, 2023 05:52
Show Gist options
  • Save moxet/8231b4741e7ae3d49ee8699abb67cb2e to your computer and use it in GitHub Desktop.
Save moxet/8231b4741e7ae3d49ee8699abb67cb2e to your computer and use it in GitHub Desktop.
Calculate Reading Time & Store in Meta Field
function calculate_reading_time() {
if (is_single()) {
global $post;
// Adjust the words-per-minute rate according to your preference
$words_per_minute = 200;
// Get the post content
$content = get_post_field('post_content', $post->ID);
// Strip shortcodes and HTML tags from the content
$stripped_content = strip_tags($content);
$word_count = str_word_count($stripped_content);
// Calculate reading time in minutes
$reading_time_minutes = ceil($word_count / $words_per_minute);
// Save reading time as post meta, remove minutes if you need int value.
update_post_meta($post->ID, 'reading_time', $reading_time_minutes." minutes");
}
}
add_action('wp', 'calculate_reading_time');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment