warm__tape
warm__tape

Reputation: 80

Replace ajax add to cart for specific products based on a custom field in Woocommerce

I've got AJAX add to cart enabled for my products which works great for 95% of them.

There are a few for which I need to disable the AJAX add to cart, so users are forced to go to the single product page and add to cart from there. I would be wanting to disable it based on the value of a custom meta key called "customizable_product" which is just a checkbox.

Is this achievable? I've searched around and haven't been able to find any information.

Upvotes: 1

Views: 408

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253783

Updated: This can be done with the following hooked function, that will display a custom button linked to the single product page for a custom fields:

// Replacing the button add to cart by a link to the product in Shop and archives pages
add_filter( 'woocommerce_loop_add_to_cart_link', 'conditionally_replacing_ajax_add_to_cart_button', 10, 2 );
function conditionally_replacing_ajax_add_to_cart_button( $button, $product  ) {

    $custom_field = get_post_meta( $product->get_id(), 'customizable_product', true );

    // When custom field exist
    if( ! empty( $custom_field ) ){
        $button_text = __("View product", "woocommerce");
        $button = '<a class="button" href="' . $product->get_permalink() . '">' . $button_text . '</a>';
    }
    return $button;
}

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

Upvotes: 1

Related Questions