For example :
- A = 21
- B = 22
- C = 23
如何使用23个子ID获取21和22个ID?
答案 0 :(得分:2)
要从产品类别字词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()
答案 1 :(得分:0)
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>";
答案 2 :(得分:0)
获取父母ID的最快方法是使用Wordpress提供并记录的内置函数。参见get_ancestors
如果您已选中get_term_parents_list,则会看到它使用了get_ancestors,请参阅此链接 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');