WordPress文章页面调用相同分类下文章列表
要在WordPress文章页面中调用相同分类下的文章列表,你可以使用WordPress的WP_Query类或使用内置的shortcode。以下是两种方法:

方法1:使用WP_Query
在文章页面的模板文件中,你可以使用WP_Query来检索相同分类下的文章列表,并将它们显示在文章页面中。以下是一个示例:
<?php
// 获取当前文章的分类
$categories = get_the_category();
if (!empty($categories)) {
    $category_ids = array();
    foreach ($categories as $category) {
        $category_ids[] = $category>term_id;
    }
    // 构建查询参数
    $args = array(
        'cat' => $category_ids[0], // 选择第一个分类
        'post__not_in' => array(get_the_ID()), // 排除当前文章
        'posts_per_page' => 5, // 显示的文章数量
    );
    // 创建新的WP_Query实例
    $related_query = new WP_Query($args);
    // 循环显示相关文章
    if ($related_query>have_posts()) {
        echo '<h2>相关文章</h2>';
        echo '<ul>';
        while ($related_query>have_posts()) {
            $related_query>the_post();
            echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
        }
        echo '</ul>';
    }
    // 重置WP_Query
    wp_reset_postdata();
}
?>方法2:使用内置shortcode
如果你不想在模板文件中添加代码,你也可以使用WordPress内置的shortcode功能。首先,在主题的functions.php文件中添加以下代码:
function related_posts_shortcode($atts) {
    $atts = shortcode_atts(array(
        'count' => 5, // 显示的文章数量
    ), $atts);
    // 获取当前文章的分类
    $categories = get_the_category();
    if (!empty($categories)) {
        $category_ids = array();
        foreach ($categories as $category) {
            $category_ids[] = $category>term_id;
        }
        // 构建查询参数
        $args = array(
            'cat' => $category_ids[0], // 选择第一个分类
            'post__not_in' => array(get_the_ID()), // 排除当前文章
            'posts_per_page' => $atts['count'],
        );
        // 创建新的WP_Query实例
        $related_query = new WP_Query($args);
        // 循环显示相关文章
        if ($related_query>have_posts()) {
            $output = '<h2>相关文章</h2>';
            $output .= '<ul>';
            while ($related_query>have_posts()) {
                $related_query>the_post();
                $output .= '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
            }
            $output .= '</ul>';
        }
        // 重置WP_Query
        wp_reset_postdata();
        return $output;
    }
}
add_shortcode('related_posts', 'related_posts_shortcode');现在,你可以在文章页面的内容中使用以下shortcode来显示相关文章列表:
[related_posts count="5"]这将在文章页面中显示当前文章相同分类下的5篇相关文章。你可以根据需要更改count参数的值。
 
                        仍然有问题? 我们要如何帮助您? 
                    
                 
             
             
             
             
        

 
                        