首页 > 解决方案 > WordPress:如何防止使用functions.php显示子类别的帖子?

问题描述

如何仅显示父类别下的帖子但隐藏子类别下的帖子?

谢谢!

标签: phpwordpress

解决方案


将此代码放在functions.php下

add_action('pre_get_posts', 'filter_out_children');

function filter_out_children( $query ) {
  if ( is_main_query() && is_category() && ! is_admin() ) {
     $qo = $query->get_queried_object();
     $tax_query = array(
       'taxonomy' => 'category',
       'field' => 'id',
       'terms' => $qo->term_id,
       'include_children' => false
     );
     $query->set( 'tax_query', array($tax_query) );
  }
}

推荐阅读