Created
June 21, 2023 05:52
-
-
Save moxet/8231b4741e7ae3d49ee8699abb67cb2e to your computer and use it in GitHub Desktop.
Calculate Reading Time & Store in Meta Field
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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