wordpress调用指定分类ID下 相同标签的内容

要在WordPress中调用分类ID为1、3、7的分类下,具有相同标签的前10个内容,可以使用自定义的WordPress查询(WP_Query)。以下是实现此功能的步骤和示例代码:

步骤:

确定共同标签:

首先,你需要确定分类1、3、7下所有文章共有的标签。这可以通过查询这些分类下的所有标签并找出交集来实现。

执行主查询:

使用WP_Query来查询属于分类1、3、7且具有上述共同标签的文章,并限制结果为10篇。

示例代码:

<?php
$post_num = 10; 
$specific_cat_ids = array(1, 3, 7);

// 获取当前文章的标签并转换为字符串
$tags = '';
if ( get_the_tags() ) {
    $tags = implode('-', array_map(function($tag) {
        return sanitize_title($tag->name);
    }, get_the_tags()));
}

$myposts = array();
foreach ( $specific_cat_ids as $catid ) {
    $args = array(
        'posts_per_page' => $post_num,
        'category' => $catid,
        'tag' => $tags,
        'post__not_in' => array(get_the_ID()),
        'suppress_filters' => false // 确保不会过滤掉任何帖子
    );

    $query = new WP_Query($args);
    if ($query->have_posts()) {
        while ($query->have_posts()) {
            $query->the_post();
            $myposts[] = $post;
        }
    }
    wp_reset_postdata(); // 重置后一个查询后的数据
}

if ( !empty($myposts) ) {
    foreach ( $myposts as $post ) {
        setup_postdata($post);
?>
        <li class="media mb-2 pb-2" style="border-bottom:dashed 1px #f3f3f3;">
            <div class="media-body">
                <a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"><span class="text-customer">&bull;</span> <?php the_title(); ?></a>
            </div>
        </li>
<?php
    }
    wp_reset_postdata(); // 重置全局$post数据
}
?>

推荐模板