John Davidson

php - I'm trying to disable the buy buttons on my WordPress site for products that are virtual

0 comments
Message:


as the title states, I'm trying to remove the buy button for virtual products. I am using the Astra theme in WordPress alongside Woocommerce, and Elementor.


Now my issue is that with my current implementation, it does remove the button from the individual product page. However it still displays the button on the categories page, which is a pain. I have tried setting the price to nothing, and while that does work. It doesn't help as I still want the products to have their prices listed.


I have added the following code to the functions.php section of my duplicated theme file;


function buy_filter()
{
if ( ! is_product() ) return;

$product = get_product();

if ($product->is_virtual('yes'))
{
//$product->is_purchasable('false')

//remove_action( 'woocommerce_before_shop_loop', 'woocommerce_result_count', 20 );
//remove_action('woocommerce_before_shop_loop', 'woocommerce_catalog_ordering', 30);

remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart' );
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30);
remove_action( 'woocommerce_simple_add_to_cart', 'woocommerce_simple_add_to_cart', 30);
remove_action( 'woocommerce_grouped_add_to_cart', 'woocommerce_grouped_add_to_cart', 30);
remove_action( 'woocommerce_variable_add_to_cart', 'woocommerce_variable_add_to_cart', 30);
remove_action( 'woocommerce_external_add_to_cart', 'woocommerce_external_add_to_cart', 30);
}
}

add_action ('wp', 'buy_filter');

Any help would be greatly appreciated, and I'm happy to give any more details I can to aid in the matter.


Thank you kindly!



My Answer:
To remove the buy button for virtual products on the categories page as well, you can modify your code as follows:

php
function buy_filter()
{
global $product;

if ( $product->is_virtual() ) {
remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10 );
}
}

add_action ('wp', 'buy_filter');


This code will check if the product is virtual and remove the add to cart button on the categories page as well. Make sure to replace `is_virtual('yes')` with `is_virtual()` as the `is_virtual()` function does not take any arguments.

Additionally, you can also add the following CSS to hide the button completely if needed:

css
.woocommerce ul.products li.product .button {
display: none;
}


Add this CSS to your theme's custom CSS or in the Additional CSS section in the WordPress Customizer.

I hope this helps! Let me know if you have any further questions.

Rate this post

3 of 5 based on 9831 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us