Php WordPress/Woocommerce:如何从父类别id通过“id”获取特定的子类别
我发现一个很好的代码如下所示 它工作的很好,但我需要得到一个特定的儿童类别的“id”。 例如,如果代码的输出为: 红色的 蓝色 绿色 黄色的 如何仅获取绿色,因为我需要进行另一个查询以在中使用它Php WordPress/Woocommerce:如何从父类别id通过“id”获取特定的子类别,php,woocommerce,categories,Php,Woocommerce,Categories,我发现一个很好的代码如下所示 它工作的很好,但我需要得到一个特定的儿童类别的“id”。 例如,如果代码的输出为: 红色的 蓝色 绿色 黄色的 如何仅获取绿色,因为我需要进行另一个查询以在中使用它 'tax_query'=>array('field'=>'id') 以下是函数: //woocommerce get sub categories from parent id function woocommerce_subcats_from_parentcat
'tax_query'=>array('field'=>'id')
以下是函数:
//woocommerce get sub categories from parent id
function woocommerce_subcats_from_parentcat_by_ID($parent_cat_ID) {
$args = array(
'hierarchical' => 1,
'show_option_none' => '',
'hide_empty' => 0,
'parent' => $parent_cat_ID,
'taxonomy' => 'product_cat'
);
$subcats = get_categories($args);
foreach ($subcats as $sc) {
$link = get_term_link( $sc->slug, $sc->taxonomy );
echo $sc->name.'</br>';
}
}
以下是我必须获取类别的特定id的代码:
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
global $product;
$product = $cart_item['data'];
if ( has_term( 'phone-model', 'product_cat', $product->id ) ) {
$cat_check = true;
$term_list = wp_get_post_terms( $product->id,'product_cat',array('fields'=>'ids'));
$cat_id = (int)$term_list[0];
$funspecificsub = woocommerce_subcats_from_parentcat_by_ID($cat_id);
$args = array(
'post_type' => 'product',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'id', //This is optional, as it defaults to 'term_id'
'terms' => $funspecificsub,
'include_children' =>true
)
)
);
$loop = new WP_Query( $args );
$i=1;
while ( $loop->have_posts() ) : $loop->the_post();
global $product;
if($product->is_visible()){
echo '<li style=">';
echo '<a id="cover_'.$i.'" class=" '.$product->id.'" >';
echo '<div class="">'.get_site_url().'/?add-to-cart='.$product->id.'</div>';
echo '<h5>'.get_the_title().'</h5>';
echo '<h6>'.wc_price($product->get_price_including_tax(1,$product->get_price())).'</h6>';
echo '</a>';
echo '</li>';
}else{}
$i++;
endwhile;
wp_reset_query();
}
}
所以我想主要的问题是如何在上面的变量$funsecificsub中获得“绿色”类别id。目前,它正在输出所有子类别。我希望能够选择特定的子类别。你说的“如何获得绿色”是什么意思?您已经得到“绿色”,因为您的函数刚刚输出它。真的不清楚你到底想问什么。在得到子类别后,我需要进行另一个查询,从中只选择一个类别。而且没有必要否决@cbroe,这仍然不能解释你的实际问题。您在哪一步上遇到问题?检查我更新了问题@CBroe“我希望能够选择特定的一个”–在哪里/何时/如何?