通过父类别插件从子类别中获取帖子

时间:2017-12-04 作者:Nikko Dela Cruz

我想获得特定父类别的子类别列表,并显示其帖子和子类别名称。

Note: 我在用woocommerce

Ex:父类别1-子类别1 the\\u post()-子类别2 the\\u post()-子类别3 the\\u post();

到目前为止,我已经有了代码,但我不知道如何实现它。

$query_args = array(
           \'post_type\' => \'product\',
           \'tax_query\' => array(
                array(
                    \'taxonomy\' => \'product_cat\',
                    \'field\'    => \'slug\',
                    \'terms\'    =>  \'home-furnitures\'
                ),
            ),
         );

1 个回复
最合适的回答,由SO网友:Narek Zakarian 整理而成

您可以这样做:

1-获取属于所需术语的所有子术语

$args = array(
    \'taxonomy\' => \'product_cat\',
    \'child_of\'      => 7, put here the id of parent term, which chldren you want to get
    \'hide_empty\' => false,
);
$child_terms = get_terms( $args );
2-循环浏览这些术语并打印出这些名称和帖子

if(!empty($child_terms)){
    foreach($child_terms as $term){
        $args = array(
            \'posts_per_page\'   => -1,
            \'post_type\'        => \'product\',
            \'tax_query\' => array(
                array(
                    \'taxonomy\' => \'product_cat\',
                    \'field\' => \'term_id\',
                    \'terms\' => $term->term_id,
                )
            ),
            \'post_status\'      => \'publish\',
        );
        $posts_array = get_posts( $args );

        echo $term->name; // subterm name

        foreach ($posts_array as $post) {
            setup_postdata( $post );
            the_title(); //subterm post
        }
    }
}

结束

相关推荐