phpwordpresswoocommerceproducttaxonomy-terms

Disable products purchases that don't have specific tags in WooCommerce


/*
 * Disable buying products from specific category and tag
 *
 * @author Misha Rudrastyh
 * @url https://rudrastyh.com/woocommerce/make-products-non-purchasable.html#specific-categories
 */
add_filter( 'woocommerce_is_purchasable', 'misha_catalog_mode_on_for_category', 10, 2 );
function misha_catalog_mode_on_for_category( $is_purchasable, $product ) {
    
    // Second – check product tags
    if( has_term( 'available', 'product_tag', $product->get_id() ) ) {
        $is_purchasable = true;
    }
    
    return $is_purchasable;
}

I want to enable add to cart button only for the products with tag called available and make add to cart button hidden on rest of the products on WooCommerce.

I have tried to enable add to cart button on the selected products with tag available but it doesn't disable other products.


Solution

  • To make all products unavailable on WooCommerce except those with the tag available, you need to make is purchasable false before you make it true only if your condition is met.

    /*
     * Disable buying products from specific category and tag
     *
     * @author Misha Rudrastyh
     * @url https://rudrastyh.com/woocommerce/make-products-non-purchasable.html#specific-categories
     */
    add_filter( 'woocommerce_is_purchasable', 'misha_catalog_mode_on_for_category', 10, 2 );
    function misha_catalog_mode_on_for_category( $is_purchasable, $product ) {
        $is_purchasable = false;
        // Second – check product tags
        if( has_term( 'available', 'product_tag', $product->get_id() ) ) {
            $is_purchasable = true;
        }
        
        return $is_purchasable;
    }