【问题标题】:Show posts from only one subcategory - Wordpress仅显示一个子类别的帖子 - Wordpress
【发布时间】:2013-04-22 13:09:12
【问题描述】:

假设我有以下类别。

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();
 ?> 

【问题讨论】:

  • 举个例子,对于不熟悉WordPress的人来说,一般如何显示结果
  • 显示您尝试过的代码。
  • 嗨 Royal 和 Rikesh,我添加了一个示例代码。目前我不知道如何显示子类别中的帖子。此代码将显示一个类别及其子类别中的所有帖子。

标签: php wordpress


【解决方案1】:

看起来您使用的示例过于复杂。如果您只需要特定类别的帖子,那么您可以使用类别 slug 或 ID 来检索帖子,并像上面的示例一样使用 WP_Query。

因此,如果“流行”类别的 id 为 4(您可以通过将鼠标悬停在帖子中的类别名称上来获取类别 ID -> 类别...它显示在编辑链接中),那么您的代码将是;

<?php
$result = new WP_Query( 'cat=4' );

while ($result->have_posts()) : $result->the_post(); 
?>

这是 Codex 的相关部分;

https://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters

【讨论】:

    【解决方案2】:

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

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

    $verticalNavigationSwitcher = "category__in=$catID&orderby=ID&order=ASC";
    

    【讨论】:

      猜你喜欢
      • 2016-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-19
      • 1970-01-01
      相关资源
      最近更新 更多