如何通过将以下代码片段添加到 WordPress 主题的 functions.php
文件中,来为您的文章显示预计阅读时间。可以帮助您的读者了解每篇文章所需的大致阅读时间。
1. 找到您的 functions.php
文件
- 编辑到您当前使用的主题目录,通常位于
wp-content/themes/your-theme-name/
- 找到
functions.php
文件并使用文本编辑器打开它。
2. 将代码片段添加到 functions.php
将以下代码复制并粘贴到 functions.php
文件的末尾:
// Estimated reading time
function article_reading_time($content) {
if (is_single()) { // Only display on single article pages
// Remove HTML tags, keep content inside code blocks
$text = strip_tags($content, '<pre><code>');
// Keep only Chinese, English characters, and numbers; remove other characters
$text = preg_replace('/[^a-zA-Z0-9\x{4e00}-\x{9fa5}]/u', '', $text);
// Calculate word count (only count Chinese, English, and number characters)
$word_count = mb_strlen($text, 'UTF-8');
// Calculate estimated reading time, assuming 300 words per minute
$reading_time = ceil($word_count / 300);
// Display estimated reading time with updated colors
$output = '<div class="post-meta" style="padding: 12px; background: #FFF4E5; border-left: 5px solid #FF7300;
margin-bottom: 15px; font-size: 16px; line-height: 1.6; color: #A74C00;">';
$output .= '<strong>预计阅读时间:</strong> ' . $reading_time . ' 分钟';
$output .= '</div>';
return $output . $content; // Insert reading time before article content
}
return $content;
}
add_filter('the_content', 'article_reading_time');
代码解释:
- 这段代码会在每篇文章的开头显示预计阅读时间。
article_reading_time
函数会提取文章中的中文、英文和数字字符,然后根据每分钟阅读 300 个字的假设,计算出预计阅读时间。- 最后,这段代码会在文章内容的上方显示预计阅读时间。
3. 保存 functions.php
文件
- 保存对
functions.php
文件的更改。
4. 查看效果
现在,您可以访问任意一篇文章页面,您应该能够看到每篇文章上方会显示一个类似这样的标签:
预计阅读时间:X 分钟
这里的 X
会根据每篇文章的字数动态变化。
发表回复