Home > database >  Add custom CSS class to "add to cart" button on WooCommerce shop and archives pages based
Add custom CSS class to "add to cart" button on WooCommerce shop and archives pages based

Time:01-13

I am trying to disable "add to cart" button on WooCommerce shop and archives pages if product's quantity stock is zero or less.

I don't want to hide it so I came up with the code below.

My issue is that code doesn't add style to element, it replaces the whole button code inside html tree so button is not displayed at all.

Any ideas on how to overcome the issue?

add_action( 'woocommerce_loop_add_to_cart_link', 'remove_price_from_variable_products', 9 );

function remove_price_from_variable_products() {
    global $product;

    if( $product->get_stock_quantity() <= 0 ) {
    ?>
    <style> 
        .add_to_cart_button {
            cursor: not-allowed !important;
        }
    </style>
    <?php
        
add_action( 'woocommerce_after_shop_loop_item', 'custom_content_addtocart_button', 100 );

    }
}


function custom_content_addtocart_button() {
    echo '<br/><div >Contact Us for more information</div>';
} 

CodePudding user response:

To add/edit/remove CSS classes from the existing add to cart button on WooCommerce shop and archives pages you can use the woocommerce_loop_add_to_cart_args filter hook

So you get:

function action_woocommerce_loop_add_to_cart_args( $wp_parse_args, $product ) {
    // Initialize
    $custom_class = '';
    
    // Not allowed
    if ( $product->get_stock_quantity() <= 0 ) {
        $custom_class = 'button-not-allowed';
    }
    
    // NOT empty
    if ( ! empty ( $custom_class ) ) {  
        // Class
        $wp_parse_args['class'] = implode(
            ' ',
            array_filter(
                array(
                    'button' . ' ' . $custom_class,
                    'product_type_' . $product->get_type(),
                    $product->is_purchasable() && $product->is_in_stock() ? 'add_to_cart_button' : '',
                    $product->supports( 'ajax_add_to_cart' ) && $product->is_purchasable() && $product->is_in_stock() ? 'ajax_add_to_cart' : '',
                )
            )
        );
    }

    return $wp_parse_args;
}
add_filter( 'woocommerce_loop_add_to_cart_args', 'action_woocommerce_loop_add_to_cart_args', 10, 2 );

Note: the $product->get_stock_quantity() function is best used in combination with $product->managing_stock(), but this depends on your needs


Then apply the following CSS

.button-not-allowed {
    cursor: not-allowed !important;
}
  •  Tags:  
  • Related