WordPress在文章中添加相关文章推荐功能

添加一段代码,它通过分析文章的分类,智能地在单篇文章末尾展示相关文章,从而提升网站的互动性和用户体验。

1. 找到您的 functions.php 文件

  • 编辑到您当前使用的主题目录,通常位于 wp-content/themes/your-theme-name/
  • 找到 functions.php 文件并使用文本编辑器打开它。

2. 将代码片段添加到 functions.php

将以下代码复制并粘贴到 functions.php 文件的末尾:

// Related articles
function display_related_posts_by_category($content) {
    if (is_single()) {
        $post_object = get_queried_object();
        if ($post_object) {
            $categories = wp_get_post_categories($post_object->ID);
            if ($categories) {
                $args = array(
                    'category__in' => $categories,
                    'post__not_in' => array($post_object->ID),
                    'posts_per_page' => 5,
                    'orderby' => 'rand',
                    'no_found_rows' => true,
                );
                $related_posts = new WP_Query($args);
                if ($related_posts->have_posts()) {
                    $content .= '<div class="related-posts"><h3>相关文章</h3><ul>';
                    while ($related_posts->have_posts()) {
                        $related_posts->the_post();
                        $content .= '<li><a href="' . esc_url(get_permalink()) . '">' . esc_html(get_the_title()) . '</a></li>';
                    }
                    $content .= '</ul></div>';
                    wp_reset_postdata();
                }
            }
        }
    }
    return $content;
}
add_filter('the_content', 'display_related_posts_by_category');

3. 保存 functions.php 文件

  • 保存对 functions.php 文件的更改。

4. 实际应用:增强用户体验

通过在 WordPress 网站中添加这段代码,可以实现以下效果:

  • 提高用户粘性: 相关文章的推荐,能够引导用户浏览更多感兴趣的内容,延长页面停留时间。
  • 优化内容结构: 通过分类推荐,帮助用户发现同一主题下的其他文章,完善内容体系。
  • 提升 SEO 效果: 增加页面内部链接,有助于搜索引擎更好地理解网站结构和内容相关性。

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注