0

I want to add a back button to the Single Product page so that the page will be redirected to the relevant parent category page of the product upon clicking. I have managed to get this done for one category using the following code. Here it will redirect the page to the shirts category upon clicking the back to designs button.

add_action( 'woocommerce_before_single_product', 'content_before_addtocart_button' );

function content_before_addtocart_button() {
    global $post;

    $terms = get_the_terms( $post->ID, 'product_cat' );
    
    foreach ($terms as $term) {
        if( $term->slug === 'shirts')
            echo '<div class="content-section"><a href="' . esc_url( get_term_link( $term->term_id, 'product_cat' ) ) . '">' . 'Back to Other Designs'. '</a></div>';
    }
}

I want to modify this so that it will get the current category page link of the product automatically without adding them manually like this and redirect the page accordingly. Any help on this is highly appreciated. Thanks in advance.

1
  • Do you have one category attached to each product, or a single product can have more than one category and you want to use one of them only? Also, should the back button text "Back to Other Designs" change according to the product category or it will be the same for any category?
    – Aboelabbas
    Commented Jul 9, 2021 at 19:28

1 Answer 1

0

Put this below code in functions.php and Try it.

add_action( 'woocommerce_before_single_product', 'content_before_addtocart_button' );
function content_before_addtocart_button() {
    global $post;
    $categories = array();
    $taxonomies = get_terms( array(
        'taxonomy' => 'product_cat',
        'hide_empty' => false,
        'parent'   => 0
    ));
    if ( !empty($taxonomies) ) :
        foreach( $taxonomies as $taxonomy ) {
            $categories[] = $taxonomy->slug; 
        }
    endif;
    $terms = get_the_terms( $post->ID, 'product_cat' );
    if($terms[0]->parent != 0){
        $parent_category = get_term( $terms[0]->parent, 'product_cat' );
        $parent_category_slug = $parent_category->slug;
        foreach ($terms as $term) {
            if(in_array( $parent_category_slug ,$categories )){
                echo '<div class="content-section"><a href="' . esc_url( get_term_link( $term->term_id, 'product_cat' ) ) . '">' . 'Back to Other Designs'. '</a></div>';
            }
        }
    }else{
        echo '<div class="content-section"><a href="' . esc_url( get_term_link( $terms[0]->term_id, 'product_cat' ) ) . '">' . 'Back to Other Designs'. '</a></div>';
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.