我编写了自己的函数,以便从循环中排除子类别的帖子,因为我发现上面的代码对我不起作用。
在我的主题存档中。php文件,在循环上方,我列出了子类别:
<?php
$current_cat = get_queried_object();
$args = array( \'parent\'=>$current_cat->term_id, \'child_of\' => $current_cat->term_id, );
$categories = get_categories( $args );
foreach($categories as $category) { ?>
<h2><?php echo $category->name ;?></h2>
<p> etc....</p>
<?php } ?>
在我的功能中。php文件中,我使用pre\\u get\\u posts添加了以下自定义函数:
add_action( \'pre_get_posts\', \'main_query_without_subcategory_posts\' );
function main_query_without_subcategory_posts( $query ) {
if ( ! is_admin() && $query->is_main_query() ) {
// Not a query for an admin page.
// It\'s the main query for a front end page of your site.
if ( is_category() ) {
//Get the current category
$current_category = get_queried_object();
//get the id of the current category
$current_cat_id = $current_category->term_id;
//find the children of current category
$cat_args = array( \'parent\'=>$current_category->term_id, \'child_of\' => $current_category->term_id, );
$subcategories = get_categories( $cat_args );
//Get a list of subcategory ids, stick a minus sign in front
$subcat_id = array();
foreach($subcategories as $subcategory) {
$subcat_id[] = " -". $subcategory->term_id;
}
//join them together as a string with a comma seperator
$excludesubcatlist = join(\',\', $subcat_id);
//If you have multiple parameters, use $query->set multiple times
$query->set( \'posts_per_page\', \'10\' );
$query->set( \'cat\', \'\'.$current_cat_id.\',\'.$excludesubcatlist.\'\' );
}
}
}
然后在存档中。php,在子类别下面,我添加了常规WordPress循环,该循环现在正被上述函数修改:
<?php while (have_posts() ) : the_post(); ?>
<h2><?php the_title();?></h2>
<p> etc....</p>
<?php endwhile;?>
虽然WordPress codex说使用“category\\uu in”会将帖子从子类别中排除,但这对我来说并不管用,子类别帖子仍在显示。
https://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters
https://developer.wordpress.org/reference/hooks/pre_get_posts/