使用wp_list_ategories排除子类别

时间:2018-01-16 作者:Dev

$category = get_category( get_query_var( \'cat\' ) );

$child_cats = (array) get_term_children( $category , \'category\' );

wp_list_categories( array(
        \'exclude\'  => $child_cats
    ) );
是否可以排除所有子类别?

更新:我也试过了,但没用。

$categories = get_categories( array(
        \'childless\'  => true,
    ) );

    $child_cats = (array) get_term_children( $categories, \'category\' );

    $cats = wp_list_categories( array(
        \'exclude\' => $child_cats
    ) );
编辑2:我更愿意与此配合使用get_the_category_list

2 个回复
SO网友:yomisimie

与其排除子类别,不如仅获取没有父类别的类别(0)

    $cats = wp_list_categories( array(
        \'parent\' => 0
    ) );
这应该没有问题。

编辑:get_the_category_list() 不支持高级参数。你最好的选择是wp_get_post_categories($post_id, array(\'parent=>0\')). 这将返回一个对象数组,您必须使用foreach循环自己处理HTML。

SO网友:Toir

using this code

function rk_fix_tax_queries_on_archives( $query ) {
    // Only run this on the main query for the category archive
    if ( ! is_admin() && $query->is_category() && $query->is_main_query() ) {
        // What category is this
        $cat = $query->query_vars[\'category_name\'];
        // Build the new query args
        $tax_query = array(
            array(
                \'taxonomy\'         => \'category\',
                \'field\'            => \'slug\',
                \'terms\'            => $cat,
                \'include_children\' => false,
            ),
        );
        // Set the new query args to $query->query_vars[\'tax_query\']
        $query->set( \'tax_query\', $tax_query );
        // Setting the query args is not enough, we have to create a new tax query object
        // and force feed it to the query
        $query->tax_query = new WP_Tax_Query( $tax_query );
    }
}
add_action( \'parse_tax_query\', \'rk_fix_tax_queries_on_archives\' );
结束