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

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

4

3 回答 3

2

更新(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);

测试和工作。


添加:

您可以更好地使用 Wordpressget_ancestors()专用功能,例如在这个最近的答案线程其他相关答案中。

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

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

相关踏板:

相关文档化的 Wordpress 函数:

于 2018-08-31T10:45:46.663 回答
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>";
于 2018-08-31T11:10:57.153 回答
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');  
于 2020-04-30T09:48:40.053 回答