I need to remove the Add to cart button along with the quantity entry field for a certain category of products (e.g. legal services) from everywhere (from all pages). In doing so, leave those elements that add other plugins in the area where the add to cart button is located.
I would use this code:
// Disable products from categories (a, b, c) from being purchased no matter what
add_filter('woocommerce_is_purchasable', 'set_catalog_mode_on_for_category', 10, 2 );
function set_catalog_mode_on_for_category( $is_purchasable, $product ) {
if( has_term( array( 'a', 'b', 'c' ), 'product_cat', $product->get_id() ) ) {
return false;
}
return $is_purchasable;
}
// Hide 'Add To Cart' for variable products, but keep product variations visible
function remove_add_to_cart(){
if( has_term( array( 'a', 'b', 'c' ), 'product_cat', $product->get_id() ) ) {
remove_action( 'woocommerce_single_variation','woocommerce_single_variation_add_to_cart_button', 20 );
}
}
but then the other buttons that are added by other plugins to the ‘add to cart’ area disappear along with the button ‘add to cart’.
Then I thought maybe I could use this code:
add_action( 'woocommerce_single_product_summary', 'wp_replace_add_to_cart_btn', 31 );
function wp_replace_add_to_cart_btn() {
if( has_term( array( 'a', 'b', 'c' ), 'product_cat', $product->get_id() ) ) {
remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart');
?>
<style>div.quantity,.single_add_to_cart_button{display:none}</style>
<style>div.quantity,.qty{display:none}</style>
<script>jQuery(document).ready(function($){$('div.quantity,.single_add_to_cart_button'),remove()})</script>
<script>jQuery(document).ready(function($){$('div.quantity,.qty'),remove()})</script>
<?php
}
}
But in this case the cart button disappears only on the product page, while remaining on the archive product page (shop page).
Another disadvantage of this method is that it doesn’t work on pages where products from other categories are displayed in the Related Products widget, where the add to cart button is allowed.
Could you help refine the last code or provide a better solution.
I would not like to use plugins that turn the store into a catalog, as they have too much code and then the pages take 1-2 seconds longer to load. Please any help with the right solution.
2
Answers
It turned out that this solution works with errors. I will leave it here as the wrong solution, and below I will post a new answer with the correct solution.
This is an improved code of this solution https://stackoverflow.com/a/70434889/16275280
This code does the following:
Removing the ‘Add to cart’ and ‘Quantity’ buttons from a single item page of a certain category.
Renaming loop ‘Add to cart’ button to ‘View product’ on the Shop page, Archive Product page and in the Related Products widget.
Perhaps the only thing I missed here is changing the tooltip text for the button. Unfortunately, I haven’t figured out a way yet.