从 Woocommerce 中的子产品类别 ID 获取父产品类别 ID

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

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

如何使用 23 子 ID 获得 21 和 22 ID?

已更新(2020 年)

要从产品类别术语 ID 获取父术语 ID,请尝试以下操作(代码已注释)

// 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);

已测试并有效。


加法:

你可以更好地使用 Wordpress get_ancestors() dedicated function, like in or on those other related answers.

在这种情况下,代码将是:

// 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);

相关踏板:

  • woocommerce - How do I get the most top level category of the current product category

相关的 Wordpress 函数文档:

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>";

获取父 ID 的最快方法是使用 Wordpress 提供和记录的内置函数。参见 get_ancestors

如果你检查过 get_term_parents_list 你会看到它使用 get_ancestors 看这个 link https://core.trac.wordpress.org/browser/tags/5.4/src/wp-includes/category-template.php#L1362

所以简短的回答就在代码下面。

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