获得的*产品类别的自定义数组中WooCommerce
问题描述:
有没有什么办法让在woocomerce*产品类别列表中自定义栏目我的主题获得的*产品类别的自定义数组中WooCommerce
这里中显示他们是我使用的代码,但它返回所有类别:
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文件中,或者也存在于任何插件文件中。
经测试和工程
答
我希望这会帮助你。
解决方案:
global $post;
$prod_terms = get_the_terms($post->ID, 'product_cat');
foreach ($prod_terms as $prod_term) {
// gets product cat id
$product_cat_id = $prod_term->term_id;
// gets an array of all parent category levels
$product_parent_categories_all_hierachy = get_ancestors($product_cat_id, 'product_cat');
// This cuts the array and extracts the last set in the array
$last_parent_cat = array_slice($product_parent_categories_all_hierachy, -1, 1, true);
foreach($last_parent_cat as $last_parent_cat_value){
// $last_parent_cat_value is the id of the most top level category, can be use whichever one like
echo '<strong>' . $last_parent_cat_value . '</strong>';
}
}