For example :
- A = 21
- B = 22
- C = 23
如何使用23 sub Id获取21和22个ID?
要从产品类别术语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);
经过测试和工作。
get_term_parents_list()
get_term_by()
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>";