admin管理员组

文章数量:1415645

I want to get the list of subcategory of a specific parent category and show their post and subcategory name.

Note: I'm using woocommerce

Ex: Parent Category 1 -sub category 1 the_post(); -sub category 2 the_post(); -sub category 3 the_post();

I have the code so far but I don't know how to implement it.

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

I want to get the list of subcategory of a specific parent category and show their post and subcategory name.

Note: I'm using woocommerce

Ex: Parent Category 1 -sub category 1 the_post(); -sub category 2 the_post(); -sub category 3 the_post();

I have the code so far but I don't know how to implement it.

$query_args = array(
           'post_type' => 'product',
           'tax_query' => array(
                array(
                    'taxonomy' => 'product_cat',
                    'field'    => 'slug',
                    'terms'    =>  'home-furnitures'
                ),
            ),
         );
Share Improve this question asked Dec 4, 2017 at 13:08 Nikko Dela CruzNikko Dela Cruz 1474 silver badges15 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

You can do it this way:

1 - get all child terms which belongs the term you want

$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 - loop through these terms and print there names and posts

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
        }
    }
}

本文标签: woocommerce offtopicGet posts from subcategory by parent category slug