WordPress的 - 在父类别中列出所有类别的子帖子
问题描述:
我想能够列出浏览父类别时的所有帖子(子女和父母)。WordPress的 - 在父类别中列出所有类别的子帖子
像这样:
- 父(从儿童1儿童2显示帖子)
- 儿童1(显示自儿童1只职位)
- 儿童2(显示自独生子女帖子2)
有了下面这段代码(放在category.php)我不明白人l当我在父类别中时的帖子。我只是从一个孩子类别而不是几个类别发布帖子。
任何想法如何解决这个问题?
<?php get_header(); ?>
<div class="container">
<div class="row">
<?php get_template_part('include-cat-tag'); ?>
<div class="col-xs-12 col-sm-9 col-md-9 list-page-middle">
<header class="clearfix">
<h1><?php single_cat_title('', true); ?></h1>
</header>
<?php
wp_reset_query();
$categories = get_the_category();
$category_id = $categories[0]->cat_ID;
$args = array(
'posts_per_page' => 100,
'category__in' => array($category_id),
'orderby' => 'meta_value title',
'order' => 'ASC',
'post_status' => 'publish',
'meta_key' => 'betyg',
'child_of' => $category_id
);
query_posts($args);
if (have_posts()): while (have_posts()) : the_post();
get_template_part('include-list-post');
?>
<?php endwhile; ?>
<?php else: ?>
<?php get_template_part('include-no-post'); ?>
<?php endif; ?>
</div>
</div>
<?php
get_template_part('include-list');
get_template_part('include-social');
?>
</div>
</div>
<?php get_footer(); ?>
答
我认为您的查询存在一些问题。
- “child_of” 不支持query_posts/get_posts功能。相反,它只是get_categories的有效选项。我认为你在查询帖子和类别之间感到困惑。您可以查看parse_query或get_posts函数查看所有可用选项。
https://codex.wordpress.org/Plugin_API/Action_Reference/parse_query
https://codex.wordpress.org/Template_Tags/get_posts
“meta_key” 选项示出,但 “meta_value” 缺失。
WP也不建议直接使用query_posts,而是使用get_posts函数或挂钩到pre_get_posts操作。
要获得的类别的子类别中的所有文章列表,你可以做一些事情如下:
<?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');