Wordpress - 列出父类别中的所有类别子帖子

时间:2016-08-05 08:26:25

标签: wordpress

我希望能够在浏览父类别时列出所有帖子(儿童和父母)。

像这样:

  • 家长(显示来自儿童1和儿童2的帖子)
    • 儿童1(仅显示儿童1的帖子)
    • 儿童2(仅显示儿童2的帖子)

使用下面的代码(放在category.php中),当我在父类别中时,我不会收到所有帖子。我只收到一个子类别的帖子,而不是几个。

任何想法如何解决这个问题?

Vector3.set

1 个答案:

答案 0 :(得分:0)

我认为您的查询存在一些问题。

  1. " child_of" query_posts / get_posts 功能不支持。相反,它只是 get_categories 的有效选项。我认为你在查询帖子和类别之间感到困惑。您可以查看 parse_query get_posts 功能,查看所有可用选项。
  2. https://codex.wordpress.org/Plugin_API/Action_Reference/parse_query

    https://codex.wordpress.org/Template_Tags/get_posts

    1. " meta_key"显示的选项但是" meta_value"丢失。

    2. WP也不建议直接使用query_posts,但要使用get_posts函数或挂钩 pre_get_posts 操作。

    3. 要获取某个类别子类别的所有帖子的列表,您可以执行以下操作:

          <?php ...
           $categories = get_categories(array("child_of" => $parent_category->term_id));
      
           $posts_to_display = get_posts("category" => $parent_category->term_id);
           foreach($categories as $category){
      
           // query child posts of this category here of this category here using get_posts
      
          // then merge them to the $posts_to_display array
           }
      
          //Do what ever you want with the array
      

      或者,如果您仍想使用query_posts并且Wordpress循环不使用 get_posts ,请使用挂钩 pre_get_posts 操作:

      <?php
      function get_posts_for_parent_category( $query ) {
          // make sure that you are in the category page not single post or custom post type page
          if(!$query->is_category)
              return;
      
          $parent_category = $query->get_querried_object();
          $categories_to_query = array($parent_category->term_id);
      
          // Using get_categories to get all child categories_to_query
      
          // Get their ids and add it to the $categories_to_query array
      
          $query->set("category__in",$categories_to_query);
      }
      add_action( 'pre_get_posts', 'get_posts_for_parent_category' );
      
相关问题