wordpress - 如何在类别页面上的循环之外显示精选帖子,其中帖子必须与类别匹配
问题描述
我正在尝试在显示帖子的循环上方的所有类别页面上建立一个“热门文章”区域。我在每个帖子上添加了一个“精选帖子”复选框,允许管理员将某些帖子标记为精选帖子,并且我已经能够在每个类别页面的顶部显示这些帖子。但它目前在所有类别页面上显示所有精选帖子,我需要系统过滤帖子以仅显示与它们显示的页面属于同一类别的帖子。
这是我在我的函数文件中使用的,可以很好地显示特色帖子 - 任何添加类别过滤的帮助都非常感谢!
$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_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
}
这是它的外观示例。如您所见,所有五个帖子都与存档页面类别属于同一类别。
我希望这会有所帮助。
推荐阅读
- javascript - 如何监听 window.forward() 事件?(HTML5 历史 API)
- zsh - ZSH 清除终端并呈现命令返回数据
- php - mkdir 上的 file_put_contents 无法打开流:权限被拒绝
- python - 图片未显示在我的 QLabel 加载屏幕上
- swift - 如何为每个小部件获取不同的数据
- python - 你能制作 mpld-matplotlib 交互式图形网络应用程序吗?
- python - 通过传递函数在 Python(非实时)仿真环境中仿真子系统
- javascript - 如何使用 Google Docs API 将文本添加到 Word 文档?
- r - 提取R中2个点之间的字符
- c# - 如何使用动态枢轴c#winform将总计列和行插入datagridview