Dhirendrasinh DRC
Dhirendrasinh DRC

Reputation: 137

Get the parent product categories ids from a sub product category ID in Woocommerce

For example : 
- A = 21
  - B = 22
     - C = 23

How can I get 21 and 22 IDs using 23 sub Id?

Upvotes: 2

Views: 2824

Answers (3)

LoicTheAztec
LoicTheAztec

Reputation: 253784

Updated (2020)

To get the parent terms Ids from a product category term ID, try the following (code is commented):

// Get the parent term slugs list
$parent_terms_list = get_term_parents_list( 23, 'product_cat', array('format' => 'slug', 'separator' => ',', 'link' => false, 'inclusive' => false) );

$parent_terms_ids = []; // Initialising variable

// Loop through parent terms slugs array to convert them in term IDs array
foreach( explode(',', $parent_terms_list) as $term_slug ){
    if( ! empty($term_slug) ){
        // Get the term ID from the term slug and add it to the array of parent terms Ids
        $parent_terms_ids[] = get_term_by( 'slug', $term_slug, 'product_cat' )->term_id;
    }
}

// Test output of the raw array (just for testing)
print_r($parent_terms_ids);

Tested and works.


Addition:

You can better use Wordpress get_ancestors() dedicated function, like in this recent answer thread or on those other related answers.

In this case the code is going to be:

// Get the parent term ids array
$parent_terms_ids = $parent_ids = get_ancestors( $child_id, 'product_cat' , 'taxonomy');  

// Test output of the raw array (just for testing)
print_r($parent_terms_ids);

Related treads:

Related documented Wordpress functions:

Upvotes: 2

jameshwart lopez
jameshwart lopez

Reputation: 3131

The fastest way to get the parents ids is to use the built in function given and documented by Wordpress. See get_ancestors

if you have checked get_term_parents_list you will see that it uses get_ancestors see this link https://core.trac.wordpress.org/browser/tags/5.4/src/wp-includes/category-template.php#L1362

So the short answer is just below code.

$parent_ids = get_ancestors( $child_id, 'product_cat' , 'taxonomy');  

Upvotes: 0

Dhirendrasinh DRC
Dhirendrasinh DRC

Reputation: 137

function parentIDs($sub_category_id)
{
    static $parent_ids = [];        
    if ( $sub_category_id != 0 ) {
        $category_parent = get_term( $sub_category_id, 'product_cat' );             
        $parent_ids[] = $category_parent->term_id;
        parentIDs($category_parent->parent);
    } 
    return $parent_ids;
}
$sub_category_id = 23;
$parent_ids_array = parentIDs($sub_category_id);
echo "<pre>";
print_r($parent_ids_array);
echo "</pre>";

Upvotes: 0

Related Questions