Adding a reading time estimate can give your readers an idea of what to expect and help them manage their time better. In this article, I’ll explore how to automatically calculate the reading time of your WordPress posts and save it using Advanced Custom Fields (ACF).

Calculating Reading Time:

First, we need to create a function that calculates the reading time based on the content of the post. This function counts the number of words in the post content and estimates the reading time in minutes.

function calculate_reading_time( $content ) {
  $words = str_word_count( strip_tags( $content ) );
  $minutes = ceil( $words / 200 ); // Assuming an average reading speed of 200 words per minute
  if ( $minutes < 1 ) {
    $minutes = 1;
  }
  $reading_time = $minutes . ' minute' . ( $minutes == 1 ? '' : 's' );
  return $reading_time;
}

Saving Reading Time to ACF Field

Now, we’ll create a function that automatically calculates the reading time and saves it in an ACF field called “reading_time” every time a post is saved.

function save_reading_time( $post_id ) {
  $post_content = get_post_field( 'post_content', $post_id );
  $reading_time = calculate_reading_time( $post_content );
  update_field( 'reading_time', $reading_time, $post_id );
}
add_action( 'save_post', 'save_reading_time' );

Updating Reading Time for All Posts

If you want to update the reading time for all existing posts, you can use a custom script. This script loops through all posts, calculates the reading time, and updates the ACF field accordingly.

$args = array(
  'post_type' => 'post',
  'posts_per_page' => -1,
);

$posts = get_posts( $args );

foreach ( $posts as $post ) {
  $post_content = get_post_field( 'post_content', $post->ID );
  $reading_time = calculate_reading_time( $post_content );
  update_field( 'reading_time', $reading_time, $post->ID );
}

By implementing these steps, you can enhance your WordPress posts by displaying the estimated reading time. This not only provides valuable information to your readers but also helps them manage their time more efficiently.