新函数中的未定义变量错误

时间:2019-10-24 作者:Sh.Dehnavi

我想让函数计算用户最后一次阅读文章的时间,但在把它放进去之后fuctions.php 我看到这个错误:

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

我的代码:

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;
}
你能帮帮我吗?我认为这很容易,但我现在无法解决。谢谢

1 个回复
最合适的回答,由SO网友:Michelle 整理而成

我想这是在告诉你$post (英寸$post->ID) 未定义。请尝试以下操作:

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 ;
}

相关推荐

Div-Wrap with Functions.php in ChildTheme Using Shorcode!

我只想为一个简单样式的DIV包装器创建一个短代码。在WordPress的网站上,我想添加如下内容:[quotehead]Headline text[/quotehead] ...a normal blockquote from wordpress... 输出应为:<div class=\"block_header\">Headline text</div> 我的内部功能functions.php (在childtheme中)包含以下内容:/**