I wanted make function to count the time last the user read the article but after putting it in fuctions.php I see this error:

Notice: Undefined variable: post in /home/karnetac/public_html/wp-content/themes/karneta/functions.php on line 2 Notice: Trying to get property 'ID' of non-object in /home/karnetac/public_html/wp-content/themes/karneta/functions.php on line 2

my codes:

function sh_reading_time() {
    $content = get_post_field( 'post_content', $post->ID );
    $word_count = str_word_count( strip_tags( $content ) ); 
    $readingtime = ceil($word_count / 200);

    return $readingtime;

would you plese help me? I think it is easy but I can not fix it now. thanks


I believe that's telling you that $post (in $post->ID) is undefined. Try this instead:

function sh_reading_time() {
    $content = get_post_field( 'post_content', get_the_ID() );
    $word_count = str_word_count( strip_tags( $content ) ); 
    $readingtime = ceil($word_count / 200);

    if ($readingtime == 1) {
      $timer = " minute";
    } else {
      $timer = " minutes";
    $totalreadingtime = $readingtime . $timer;

    return $totalreadingtime ;
  • thanks for fixing the error but do you think the functon in correct? because it shows 1 always for all artivces – Sh.Dehnavi Oct 24 '19 at 15:40
  • Your posts are probably just short. I tried it with a very long post and the number does increment. "1" is the number of minutes it would take to read. I've edited the code above to include the word 'minute' or 'minutes' based on the number. – Michelle Oct 24 '19 at 15:50
  • no my post is long but not in english. in persian. is it the reason to show 1? – Sh.Dehnavi Oct 24 '19 at 16:00
  • Ah, that might be an issue. From this question / answer it looks like str_word_count isn't reliable with Arabic languages. Maybe try one of the solutions offered in either the question or answers here: stackoverflow.com/questions/13884178/… – Michelle Oct 24 '19 at 16:32
  • yes, I found ou it my self. thanks my friend – Sh.Dehnavi Oct 24 '19 at 16:34

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.