简体   繁体   中英

Hide add to cart button when product visibility is hidden in WooCommerce

Every night I load in a CSV with my suppliers products. They remove and add products in every CSV. If a product is not in the CSV anymore and it was in the CSV before, my plugin will put the product visibility on hidden. This way the link still works, so no 404 errors in search console etc, but the product is not showing in my shop.

However, some customers still land on these links from different domains, ie google. They land on the "invisible product" and they have the possibility to click on the "in cart" button while the product is not available anymore.

Therefor my question: How can I (in functions.php?) make sure that when a product's visibility is hidden, the cart button is removed (a simple display: none; will do).

I use WP Import for importing the CSV and the way products are put on visibility:hidden is like this:

function my_is_post_to_delete($is_post_to_delete, $post_id, $import) {
     // Get an instance of the product variation from a defined ID
    $my_product = wc_get_product($post_id);
    // Change the product visibility
    $my_product->set_catalog_visibility('hidden');
    // Save and sync the product visibility
    $my_product->save();
    return false;
}

So I need something like this:

If product_visibility is ' hidden ' then remove add to cart button.

You can simply use woocommerce_is_purchasable dedicated filter hook when the product catalog visibility is "hidden", this way:

add_filter('woocommerce_is_purchasable', 'filter_product_is_purchasable', 10, 2 );
function filter_product_is_purchasable( $purchasable, $product ) {
    if( 'hidden' === $product->get_catalog_visibility() ) {
        $purchasable = false;

    }
    return $purchasable;
}

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

Note: If customer has a previous cart session with the product in it, it will be removed from it.


Update - For external (or affiliate) products try to use the following instead:

add_action( 'woocommerce_single_product_summary', 'remove_product_add_to_cart_button', 4 );
function remove_product_add_to_cart_button(){
    global $product;

    if( $product->is_type('external') && 'hidden' === $product->get_catalog_visibility() ) {
        remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
    }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM