有什么方法可以在 woocomerce 中获取顶级产品类别列表,以便在我的主题中的自定义部分中显示它们
这是我使用的代码,但它返回所有类别:
function getCategoriesList() {
// prior to wordpress 4.5.0
$args = array(
'number' => $number,
'orderby' => $orderby,
'order' => $order,
'hide_empty' => $hide_empty,
'include' => $ids
);
$product_categories = get_terms( 'product_cat', $args );
// since wordpress 4.5.0
$args = array(
'taxonomy' => "product_cat",
'child_of' => 0,
'number' => $number,
'orderby' => $orderby,
'order' => $order,
'hide_empty' => $hide_empty,
'include' => $ids
);
$product_categories = get_terms($args);
$list = array();
foreach( $product_categories as $cat ){
$thumbnail_id = get_woocommerce_term_meta( $cat->term_id, 'thumbnail_id', true );
$image = wp_get_attachment_url( $thumbnail_id );
$link = get_term_link( $cat->term_id, 'product_cat' );
$list[] = array($cat->term_id, $cat->name, $image, $link);
}
return $list;
}
我最近添加了:
'child_of' => 0
但是没有任何变化。
如何使其仅适用于顶级产品类别?
为了让它工作,缺少的参数只是(但不是)
'parent' => 0
'child_of'
所以你的工作代码应该是这样的(并且会正确返回你的数组:
function getProductCategoriesList() {
// since wordpress 4.5.0
$product_categories = get_terms( $args = array(
'taxonomy' => "product_cat",
'hide_empty' => false,
'parent' => 0,
) );
$list = array();
foreach( $product_categories as $cat ){
$thumbnail_id = get_woocommerce_term_meta( $cat->term_id, 'thumbnail_id', true );
$image = wp_get_attachment_url( $thumbnail_id );
$link = get_term_link( $cat->term_id, 'product_cat' );
$list[] = array($cat->term_id, $cat->name, $image, $link);
}
return $list;
}
代码位于活动子主题(或主题)的 function.php 文件或任何插件文件中。
测试和工作
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句