Php 从Woocommerce中的子产品类别ID获取父产品类别ID
如何使用23个子Id获得21和22个Id?更新(2020) 要从产品类别术语ID获取父术语ID,请尝试以下操作(代码已注释): 测试和工作Php 从Woocommerce中的子产品类别ID获取父产品类别ID,php,wordpress,woocommerce,custom-taxonomy,taxonomy-terms,Php,Wordpress,Woocommerce,Custom Taxonomy,Taxonomy Terms,如何使用23个子Id获得21和22个Id?更新(2020) 要从产品类别术语ID获取父术语ID,请尝试以下操作(代码已注释): 测试和工作 添加: 您可以更好地使用Wordpress的专用功能,如in或on 在这种情况下,代码将是: // Get the parent term slugs list $parent_terms_list = get_term_parents_list( 23, 'product_cat', array('format' => 'slug', 'separ
添加: 您可以更好地使用Wordpress的专用功能,如in或on 在这种情况下,代码将是:
// 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函数
- 文档化的Wordpress函数
- 文档化的Wordpress函数
函数parentID($sub\u category\u id)
{
静态$parent_id=[];
如果($sub_category_id!=0){
$category_parent=get_term($sub_category_id,'product_cat');
$parent\u id[]=$category\u parent->term\u id;
parentID($category\u parent->parent);
}
返回$parent\u id;
}
$sub_category_id=23;
$parent\u id\u array=parentid($sub\u category\u id);
回声“;
print\u r($parent\u id\u array);
回声“;
获取父ID的最快方法是使用Wordpress提供和记录的内置函数。看
如果您已选中,您将看到它使用“查看此链接”
所以简短的答案就在代码下面
$parent_ids = get_ancestors( $child_id, 'product_cat' , 'taxonomy');
哇,谢谢你,工作正常:)我也使用了下面的函数,它工作正常:)函数parentId($sub_category_id){static$parent_id=[];if($sub_category_id!=0){$category_parent=get_term($sub_category_id,'product_cat');$parent_id[]=$category_parent->term_id($category_parent->parent)}返回$parent_id;}$sub_category_id=23$parent\u id\u array=parentid($sub\u category\u id);回声“;print\u r($parent\u id\u array);回声“;
// 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);
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>";
$parent_ids = get_ancestors( $child_id, 'product_cat' , 'taxonomy');