Woocommerce Can';t仅获取二级商业产品类别
我试图从woocommerce中的3个深度类别结构中获得我的第二级类别 但它也总是返回第三级Woocommerce Can';t仅获取二级商业产品类别,woocommerce,Woocommerce,我试图从woocommerce中的3个深度类别结构中获得我的第二级类别 但它也总是返回第三级 /** * Get second level cat */ function get_second_cat_level($parent_id) { $subcats = array(); $args = array( 'parent' => $parent_id, 'taxonomy' => 'product_cat',
/**
* Get second level cat
*/
function get_second_cat_level($parent_id) {
$subcats = array();
$args = array(
'parent' => $parent_id,
'taxonomy' => 'product_cat',
'orderby' => 'name',
'show_count' => 0,
'pad_counts' => 0,
'hierarchical' => 1,
'hide_empty' => 0
);
$cats = get_categories($args);
foreach ($cats as $cat) {
$subcats[] = $cat;
var_dump($cat);
}
return $cats;
}
我假设$parent\u id
是parent\u类别的字符串id。
这太疯狂了。因为似乎没有人能为我提供任何解决方案,我将分享我使用的一个解决方案。但要小心,这是非常具体的3个深度级别类别组 我创建了两个函数: 从给定类别的id、slug或名称获取类别对象的方法:
function get_product_category($field, $value) {
$authorized_fields = array(
'term_id',
'name',
'slug'
);
// Check if field and value are set and not empty
if (!isset($field) || empty($field) || !isset($value) || empty($value)) {
$response = "Error : check your args, some are not set or are empty.";
}
else {
// Check if the specified field is part of the authorised ones
if (!in_array($field, $authorized_fields)) {
$response = "Unauthorised field $field"; }
else {
// init exists var to determine later if specified value matches
$exists = false;
$product_cats = get_terms('product_cat', array(
'hide_empty' => 0,
'orderby' => 'name'
));
// the loop will stop once it will have found the matching value in categories
foreach ($product_cats as $product_cat) {
if($product_cat->$field == $value) {
$response = $product_cat;
$exists = true;
break;
}
}
if ($exists == false) {
$response = array(
"message" => "Error with specified args",
"field" => "$field",
"value" => "$value"
);
}
}
}
return $response;
}
第二个函数使用第一个函数返回第二级类别。它使用了一个参数$dep
,当单独测试为false时,它会返回我在其他地方需要的另一个结果。所以不要在意它
function get_first_child_cat_only ($cat_id, $dep = true) {
// Array which handle all the 2nd child sub cats
$subcats = array();
// $cat_id is the parent (1st level) cat id
$categories = get_term_children( $cat_id, 'product_cat' );
foreach ($categories as $sub_category) {
if ($dep == true && get_term_children( $sub_category, 'product_cat' )) {
$subcats[] = get_product_category('term_id', $sub_category);
}
elseif($dep == false) {
$subcats[] = get_product_category('term_id', $sub_category);
}
}
return $subcats;
}
小说明:上面的函数只返回具有子类别的子类别。因此,它忽略最后一个(第三个)没有子项,只返回第二个
这当然可以改进,我知道我可能会受到一些“批评”,事实上,我希望如此!所以不要犹豫:)