使用wordpress,我修改了一个自定义主题,用从网站上找到的脚本a显示文章字数和估计的阅读时间。我甚至添加了一个选项来打开/关闭它。剧本写得很好…,或者我是这么想的。
当我打开wordpress调试选项来查找主题中的错误时,我得到了这个脚本的一个错误。不过,我不认为有问题。
浏览网页时显示的错误
:
这篇文章包含
注意:未定义的变量:post-in
/主页/xxxxxx/wordpress.xxxxxx.com/wp-content/themes/xxxxxx/functions.php
在线1676
注意:试图在中获取非对象的属性
/主页/xxxxxx/wordpress.xxxxxx.com/wp-content/themes/xxxxxx/functions.php
在线1676
52个字。
这篇文章会带你到处走
注意:未定义的变量:post-in
/主页/xxxxxx/wordpress.xxxxxx.com/wp-content/themes/xxxxxx/functions.php
在线1683
注意:试图在中获取非对象的属性
/主页/xxxxxx/wordpress.xxxxxx.com/wp-content/themes/xxxxxx/functions.php
在线1683
1分钟阅读。
我复制并添加到/functions.php的脚本
/*** ADD POST WORD COUNT ***/
function word_count() {
$content = get_post_field( 'post_content', $post->ID );
$word_count = str_word_count( strip_tags( $content ) );
return $word_count;
}
/*** ADD ESTIMATED READING TIME ***/
function reading_time() {
$content = get_post_field( 'post_content', $post->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;
}
我在/functions.php中添加的选项
/* MAIN SETTINGS - Show Entry Word Count Setting */
$wp_customize->add_setting('swag_main_post_word_count', array(
'default' => 'swag-main-post-word-count-yes'
));
$wp_customize->add_control('swag_main_post_word_count', array(
'label' => 'Display Post Word Count',
'section' => 'swag_main_design',
'type' => 'select',
'choices' => array(
'swag-main-post-word-count-yes' => __('Yes'),
'swag-main-post-word-count-no' => __('No')
)
));
/* MAIN SETTINGS - Show Entry Reading Time Setting */
$wp_customize->add_setting('swag_main_post_read_time', array(
'default' => 'swag-main-post-read-time-yes'
));
$wp_customize->add_control('swag_main_post_read_time', array(
'label' => 'Display Post Read Time',
'section' => 'swag_main_design',
'type' => 'select',
'choices' => array(
'swag-main-post-read-time-yes' => __('Yes'),
'swag-main-post-read-time-no' => __('No')
)
));
在主题模板文件中:/template parts/content.php
<?php
if (isset($swag_main_post_word_count) && $swag_main_post_word_count=='swag-main-post-word-count-yes') {
echo '<div class="word-count">This post contains ';
echo '' . word_count() . '';
echo ' words.</div>';
}
?>
<?php
if (isset($swag_main_post_read_time) && $swag_main_post_read_time=='swag-main-post-read-time-yes') {
echo '<div id="reading-time">This post will take you about ';
echo '' . reading_time() . '';
echo ' to read.</div>';
}
?>
我不认为我添加的选项有问题,但我在这里添加了它以防万一。我想错在我自己抄写的剧本上。这是什么?我该怎么修?