WooCommerce – Display product child categories from specific parent

The woocommerce function get_categories() is declared in abstract-wc-product.php, because it is based on the wordpress function get_the_term_list() there is no way to get only a specific branch of a category. This absolutely isn’t the same as the wordpress function get_categories(), you can see that it is woocommerce specific by how it’s used $product->get_categories(). Besides the obvious difference in arguments you can use of course, you can get deeper into that reading and comparing the linked information.


exemplarily categoryTaxonomy tree:

product_cat
    |
    |––cat1  
    |   |––child1.1  
    |   |––child1.2  
    |   |––child1.3  
    |
    |––cat2  
        |––child2.1  
        |––child2.2  
        |––child2.3  


In your case branches would be »artist« and »art«, instead of »cat1« and »cat2«. The goal is to get only the one relevant category branch for the title you want to show. At least this is what the below code is going to achieve.

Like I said above, if you want to achieve getting only terms from a specific branch of a category/taxonomy you have to do it a different way. You have to make use of get_terms() and wp_get_post_terms() and then intersect the results.

//woocommerce product category
$taxonomies = array( 'product_cat' );

//let's get an array with ids of all the terms a post has  
$post_tids = wp_get_post_terms($post->ID, 'product_cat', array("fields" => "ids"));

//you have to change branch parent id accordingly
$id_branch_parent="111";
$args = array(
    'fields' => 'ids',
    'child_of' => $id_branch_parent
);
//let's get an array with ids of all the terms a the branch has  
$branch_tids = get_terms( $taxonomies, $args );

//intersect post and branch terms to get an array of common ids
$pnb_tids = array_intersect($post_tids, $branch_tids);

//in case of multiple ids we have to loop through them
foreach ( $pnb_tids as $tid ) {
    //get the term information by id
    $tobj = get_term_by('id', $tid, 'product_cat');
    //store the term names into an array
    $pnb_name_arr[] = $tobj->name;
}

//implode the name array, this is the result you want to echo
$pnb_term_list = implode(' – ', $pnb_name_arr);

This should give you the result you want, but it’s untested.

Leave a Comment