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

问题描述 投票:1回答:2
For example : 
- A = 21
  - B = 22
     - C = 23

如何使用23 sub Id获取21和22个ID?

php wordpress woocommerce custom-taxonomy
2个回答
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);

经过测试和工作。



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>";
© www.soinside.com 2019 - 2024. All rights reserved.