Squish
Squish

Reputation: 457

WordPress WooCommerce display product category on every product button

In Woocommerce, each product button is default to product image, product name, price and an add to cart button. However, I want to add which category that product belongs to (which will direct the user to the category page) in each product button.

How can i do that?

This is an example of what I want to achieve:

enter image description here

Upvotes: 1

Views: 1374

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253773

This is possible using this custom function hooked in woocommerce_loop_add_to_cart_link filter hook, this way:

// Shop pages: we replace the button add to cart by a link to the main category archive page
add_filter( 'woocommerce_loop_add_to_cart_link', 'custom_text_replace_button', 10, 2 );
function custom_text_replace_button( $button, $product ) {
    // Get the product categories  IDs
    $category_ids = $product->get_category_ids();

    // return normal button if no category is set or if is not a shop page
    if( empty($category_ids) || ! is_shop() ) return $button;

    // Iterating through each product category
    foreach( $product->get_category_ids() as $category_id ){
        // The product category WP_Term object
        $term_obj = get_term_by( 'id', $category_id, 'product_cat' );
        // Only for first main category
        if( $term_obj->parent == 0 ){
            break; // we stop the loop
        }
    }

    // The custom button below
    $button_text = __("Visit", "woocommerce") . ' ' . $term_obj->name;
    $button_link = get_term_link( $term_obj->slug, 'product_cat' );
    return '<a class="button" href="' . $button_link . '">' . $button_text .'</a>';
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested and works on woocommerce version 3+

Upvotes: 1

Related Questions