如何在类别页面上的循环之外显示特色帖子,其中帖子必须与类别匹配

问题描述

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

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

  $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;
?>```

解决方法

如果您只需要 category 存档页面而不是其他或自定义分类法,那么您只需要全局变量 $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
}

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

Example output

我希望这会有所帮助。