1

I have a code which calculates estimated reading time of a blog post (feel free to use it as you wish):

function estimated_reading_time( $post ) {

    $words = str_word_count( strip_tags( $post->post_content ) );

    //Average reading speed of an adult is 200-250 words per minute
    $minutes = floor( $words / 200 );
    $seconds = floor( $words % 200 / ( 200 / 60 ) );

    //At least a minute
    if ( $minutes >= 1 ) {

        $estimated_time = $minutes . ' minute' . ( $minutes == 1 ? '' : 's' ) . ', ' . $seconds . ' second' . ( $seconds == 1 ? '' : 's' );
    } 
    //Less than a minute
    else {

        $estimated_time = $seconds . ' second' . ($seconds == 1 ? '' : 's');
    }

    return $estimated_time;
}

Problem: This function is suitable for the page generating loop however it is unnessesary to run this function for every blog post in every page load in a blog. It would be smarter to save it as post meta.


Question: How to save $estimated_time as post meta to WordPress default blog post?

Are there any actions, hooks or callbacks that I could use in functions.php or in a plugin?

PS! It should save the value when post is created and also when it's edited later on..

2

You can use the action hook save_post_{post_type}, so for the post type 'post' (blog posts) it is: save_post_post. For more info see the codex.

add_action( 'save_post_post', 'sw150216_save_reading_time', 10, 3);

function sw150216_save_reading_time( $post_id, $post, $update ) {
    $reading_time = estimated_reading_time( $post );
    if ( $update ) {
        update_post_meta ( $post_id, 'reading_time', $reading_time );
    } else {
        add_post_meta( $post_id, 'reading_time', $reading_time, true );
    }
}
  • Do you use the Codex? You should. – BillK Feb 15 '16 at 21:22
  • Seriously? It states "triggered whenever a post or page is created or update". There are even examples of how to handle custom posts types. – BillK Feb 15 '16 at 21:35
  • There is the hook save_post_{post_type}, so save_post_post is just for the post-type 'post' (blog post). – Sören Wrede Feb 15 '16 at 21:37
  • I updated my code for blog posts – Sören Wrede Feb 15 '16 at 21:48
  • @N00b OK, you win. The second example shows specifically how to deal with custom post types. With a little thought that code makes it clear what to do (or not do) when ANY particular post type come along. I'm not trying to write code for you but to point out resources that will allow you to do it yourself. If you give a man a fish you feed him for a day. – BillK Feb 16 '16 at 0:57
0

Hook your function to save_post. Use add_post_meta to add the field for a new post or update if this is an edit. See the Codex for adding vs. updating custom fields.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.