仅显示一个子类别的帖子 - Wordpress

时间:2013-04-22 13:09:12

标签: php 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();
 ?> 

2 个答案:

答案 0 :(得分:0)

看起来你使用的例子比较复杂。如果您只需要特定类别的帖子,那么您可以使用类别slug或ID来检索帖子,并使用WP_Query,如上例所示。

因此,如果'Pop'类别的ID为4(您可以通过将鼠标悬停在帖子中的类别名称 - &gt;类别...以显示在编辑链接中来获取类别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

答案 1 :(得分:0)

我找到了一种只显示一个子类别帖子的方法。

如果我在查询中使用“category__in”,它将返回一个类别帖子。

$verticalNavigationSwitcher = "category__in=$catID&orderby=ID&order=ASC";
相关问题