0

I am using the code below to change the "Add to Cart" to "Read More" and link to the product page. My question is how to do that ONLY for specific product categories.

add_filter( 'woocommerce_loop_add_to_cart_link', 'replace_loop_add_to_cart_button', 10, 2 );
if( $product->is_type( 'variable' ) ) return $button;
$button_text = __( "Read More", "woocommerce" );
return '<a class="button" href="' . $product->get_permalink() . '">' . $button_text .          '</a>';
}

1 Answer 1

1

You can just add another check within that filter - get the category of the product the filter is currently active on and compare it with the category you want to target.

add_filter( 'woocommerce_loop_add_to_cart_link', 'replace_loop_add_to_cart_button', 10, 2 );
function replace_loop_add_to_cart_button( $button, $product  ) {
    if( $product->is_type( 'variable' ) ) return $button;

    // array of slugs for the categories you want to target
    $target_categories = array('target_category_slug1', 'target_category_slug2'); // add more as needed

    foreach ($target_categories as $category) {
        // check if product has the category
        if ( has_term( $category, 'product_cat', $product->get_id() ) ) {
            $button_text = __( "Read More", "woocommerce" );
            return '<a class="button" href="' . $product->get_permalink() . '">' . $button_text . '</a>';
        }
    }

    // return default button if product doesn't belong to the target categories
    return $button;
}

You can replace the elements in the $target_categories with your target category slugs. This will return the "Read More" text if the product belongs to that category array, or return the default button if it isn't.

1
  • It works perfectly, thanks @Alex
    – geoplous
    Commented May 24, 2023 at 4:58

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.