I have the following code to back button but I want to display the previous category/parent category on the button it does not work as it only shows the current category name in button.
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> ';
}
}
I had a look at the following code but it only brings up the parent category id and not the name.
https://stackoverflow.com/a/53705291/15581453
CodePudding user response:
I did some changes on your code.
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> ';
}
}