Mateusz Delegacz
Mateusz Delegacz

Reputation: 11

Add a product category linked button to Woocommerce single product pages

I am trying to add a link to single product page that goes back to category page of that product

add_action ('woocommerce_before_single_product','add_backbtn_fcategory', 5);

function add_backbtn_fcategory(){

$category_id = get_cat_ID();

$category_link = get_category_link( $category_id );

?>

<a href="<?php echo esc_url( $category_link ); ?>" title="Category Name">BACK</a>

<?php
}

Effect of that is that single product page does not render below hook where the function is placed

Upvotes: 1

Views: 1911

Answers (2)

LoicTheAztec
LoicTheAztec

Reputation: 253773

As you can have many product categories set for a product, you will use the following (commented):

add_action ('woocommerce_before_single_product','add_back_product_category_button', 5);
function add_back_product_category_button(){

    // Get the product categories set in the product
    $terms = wp_get_post_terms( get_the_id(), 'product_cat' );

    // Check that there is at leat one product category set for the product
    if(sizeof($terms) > 0){
        // Get the first product category WP_Term object
        $term = reset($terms);
        // Get the term link (button link)
        $link = get_term_link( $term, 'product_cat' );

        // Button text
        $text = __('Back to','woocommerce') . ' <strong>' . $term->name . '</strong>';

        // Output
        echo '<p><a href="'.esc_url($link).'" title="'.$text.'" class="button '.$term->slug.'">'.$text.'</a></p>';
    }
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

enter image description here

Upvotes: 2

VinothRaja
VinothRaja

Reputation: 1413

global $woocommerce,$product;

$product_category_ids = wc_get_product_term_ids( $product->get_id(), 'product_cat' );

foreach( $product_category_ids as $cat_id ) {
    $term = get_term_by( 'id', $cat_id, 'product_cat' );

    echo $term->name;
}

Upvotes: 0

Related Questions