[英]Show posts from only one subcategory - Wordpress
假设我有以下类别。
Movies
----- Action
----- Science fiction
----- Drama
Music
----- POP
----- Rock
在这里,电影和音乐是父类别,其余是子类别。
如果我只想显示“音乐”类别中的POP音乐(POP帖子),我该怎么做。
请帮忙!。
我不知道如何显示子类别的帖子。 我只有的是一个示例代码,它可以显示父级和子类别的帖子。
<?
// Get the post ID
$id = get_the_ID();
//get all the categories ( this function will return all categories for a post in an array)
$category= get_the_category( $id );
if ($category->category_parent == 0) {
//extract the first category from the array
$catID = $category[0]->cat_ID;
//Assign the category ID into the query
$verticalNavigationSwitcher = "cat=$catID&orderby=ID&order=ASC";
}
$result = new WP_Query($verticalNavigationSwitcher);
//$featuredPosts->query('showposts=5&cat=3');
while ($result->have_posts()) : $result->the_post();
?>
<li><a href='<?php the_permalink() ?>'><span><?php the_title(); ?></span></a></li>
<?php
endwhile;
wp_reset_postdata();
?>
看起来您正在使用的示例使事情变得复杂。 如果仅需要特定类别的帖子,则可以使用类别标签或ID来检索帖子,并如上例所示使用WP_Query。
因此,如果“ Pop”类别的ID为4(您可以通过将鼠标悬停在“帖子”->“类别...”上的类别名称上来获取类别ID,这将显示在编辑链接中),则您的代码应为:
<?php
$result = new WP_Query( 'cat=4' );
while ($result->have_posts()) : $result->the_post();
?>
这是食典的相关部分;
https://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters
我找到了一种只显示一个子类别帖子的方法。
如果我在查询中使用“ category__in”,则返回一个类别帖子。
$verticalNavigationSwitcher = "category__in=$catID&orderby=ID&order=ASC";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.