我有以下代码返回按钮,但我想在按钮上显示以前的类别/父类别,它不起作用,因为它只显示按钮中的当前类别名称。
add_action( 'woocommerce_before_shop_loop', 'my_back_button_sample', 11 );
function my_back_button_sample() {
if ( is_product_category() ) {
//global $product;
global $wp_query;
$cate = get_queried_object();
$cateID = $cate->term_id;
$product_cat_id = $cateID;
$id = $product_cat_id;
//if( $term = get_term_by( 'id', $id, 'product_cat' ) ){
// $test = $term->name;
// $test .= "-".$term->id;
//}
$parentcats = get_ancestors($product_cat_id,'slug_name', 'product_cat');
foreach($parentcats as $parentcat){
if (is_subcategory()) {
$term = get_queried_object();
$parent_id = $term->parent;
$parent_name = $parent_id->name;
$test = $parent_name;
}
// $test = $parentcat->name;
}
echo '<br/><div class="avia-button-wrap avia-button-left avia-builder-el-9 el_after_av_button el_before_av_button ">
<a class="avia-button avia-icon_select-no avia-color-blue avia-size-medium avia-position-left " onclick="history.back();" style="cursor: pointer;">
<span class="avia_iconbox_title">Go Back to '.$test.'</span></a></div> ';
}
}
我看了一下下面的代码,但它只显示父类别id,而不是名称。
https://stackoverflow.com/a/53705291/15581453
我对你的代码做了一些修改。
add_action( 'woocommerce_before_shop_loop', 'my_back_button_sample', 11 );
function my_back_button_sample() {
if ( is_product_category() ) {
$curr_cat = get_queried_object();
if($curr_cat->parent > 0):
$parentcats = get_ancestors($curr_cat->term_id, 'product_cat');
foreach($parentcats as $parent):
$cat = get_term($parent,'product_cat');
$cat_name = $cat->name;
endforeach;
else:
$cat_name = $curr_cat->name;
endif;
echo '<br/><div class="avia-button-wrap avia-button-left avia-builder-el-9 el_after_av_button el_before_av_button ">
<a class="avia-button avia-icon_select-no avia-color-blue avia-size-medium avia-position-left " onclick="history.back();" style="cursor: pointer;">
<span class="avia_iconbox_title">Go Back to '.$cat_name.'</span></a></div> ';
}
}