首页 > 解决方案 > 如何在类别页面上的循环之外显示精选帖子,其中帖子必须与类别匹配

问题描述

我正在尝试在显示帖子的循环上方的所有类别页面上建立一个“热门文章”区域。我在每个帖子上添加了一个“精选帖子”复选框,允许管理员将某些帖子标记为精选帖子,并且我已经能够在每个类别页面的顶部显示这些帖子。但它目前在所有类别页面上显示所有精选帖子,我需要系统过滤帖子以仅显示与它们显示的页面属于同一类别的帖子。

这是我在我的函数文件中使用的,可以很好地显示特色帖子 - 任何添加类别过滤的帮助都非常感谢!

  $args = array(
        'posts_per_page' => 5,
        'meta_key' => 'meta-checkbox',
        'meta_value' => 'yes'
    );
    $featured = new WP_Query($args);
 
if ($featured->have_posts()): while($featured->have_posts()): $featured->the_post(); ?>
<h3><a href="<?php the_permalink(); ?>"> <?php the_title(); ?></a></h3>
<p class="details">By <a href="<?php the_author_posts() ?>"><?php the_author(); ?> </a> / On <?php echo get_the_date('F j, Y'); ?> / In <?php the_category(', '); ?></p>
<?php if (has_post_thumbnail()) : ?>
 
<figure> <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail(); ?></a> </figure>
<p ><?php the_excerpt();?></p>
<?php
endif;
endwhile; else:
endif;
?>```

标签: wordpresscategoriesposts

解决方案


如果您只需要为类别存档页面而不是其他或自定义分类法,您只需要全局变量$category_name。尽管它被称为“名称”,但它实际上是类别 slug,它允许我们在tax_query将附加到查询的字段中使用它。

首先,我们将$category_name其与您的元字段一起提供并在我们的查询中使用:

global $category_name;

$featured_posts = new WP_Query(
    [
        "showposts"  => 5,
        "meta_key"   => "meta-checkbox",
        "meta_value" => "yes",
        "tax_query"  => [
            [
                "taxonomy" => "category",
                "field"    => "slug",
                "terms"    => $category_name,
            ],
        ]
    ]
);

这将为我们提供以下帖子

  • 在当前分类存档页面的分类内,
  • 由管理员通过元键标记为特色帖子。meta-checkbox

现在我们可以使用这些帖子并循环浏览它们。这是一个非常简单的循环,几乎没有标记:

if ($featured_posts->have_posts()) {
    while ($featured_posts->have_posts()) {
        $featured_posts->the_post();
        ?>
         <h3>
             The post "<?php the_title(); ?>" is in category "<?php the_category(" "); ?>"
         </h3>
        <?php
    }
}
else {
    ?>
    <h3>No featured posts were found :(</h3>
    <?php
}

这是它的外观示例。如您所见,所有五个帖子都与存档页面类别属于同一类别。

示例输出

我希望这会有所帮助。


推荐阅读