1
votes

In Woocommerce single product pages, I've added a custom button using the woocommerce_after_add_to_cart hook. The button will, when clicked/ pressed, re-directs the customer to the checkout.

But to avoid the customer clicking the button before having added the product to the cart, I added this: if ( WC()->cart->get_cart_contents_count() != 0 ) { to the function.

My question is this: how can I have this button always available but inactive until a product is added to cart? How do I make it "grayed out" (not clickable) until there is a product in the cart?

Here is my complete code:

add_action('woocommerce_after_add_to_cart_button, 'instant_checkout');
function instant_checkout() {
$checkout_url = WC()->cart->get_checkout_url();
if ( WC()->cart->get_cart_contents_count() != 0 ) {
echo '<a href="'.$checkout_url.'" class="single_add_to_cart_button button alt">Instant Checkout</a>'; } }

Thanks for any help on this.

1

1 Answers

1
votes

The following will display a custom disabled button after add to cart button… When the product will be added to cart the product will be enabled and linked to checkout page:

add_action('woocommerce_after_add_to_cart_button', 'get_instant_checkout_buttom_html');
function get_instant_checkout_buttom_html() {
    global $product;

    $href = ''; // Initializing
    $class = ' disabled'; // Initializing

    // Continue only if cart is not empty
    if ( ! WC()->cart->is_empty() ) {
        // Loop through cart items
        foreach( WC()->cart->get_cart() as $item ) {
            // When product is in cart
            if( $item['product_id'] == $product->get_id() ){
                $href  = ' href="'.wc_get_checkout_url().'"'; // Add the link to the button
                $class = ''; // Remove "disabled" class
                break; // Stop the loop
            }
        }
    }
    // Button output
    echo '<a'.$href.' class="single_add_to_cart_button button alt'.$class.'">'.__("Instant Checkout").'</a>';
}

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