How to Disable add to cart button via custom checkbox

Disable add to cart button via custom checkbox in WooCommerce product settings

Explanation via comment tags added in the code
To add a checkbox to the inventory product options, use:

[php]// Add checkbox
function action_woocommerce_product_options_inventory_product_data() {
// Checkbox
woocommerce_wp_checkbox( array(
‘id’ => ‘_prevent_add_to_cart_button’, // Required, it’s the meta_key for storing the value (is checked or not)
‘label’ => __( ‘My label’, ‘woocommerce’ ), // Text in the editor label
‘desc_tip’ => false, // true or false, show description directly or as tooltip
‘description’ => __( ‘Prevent add to cart’, ‘woocommerce’ ) // Provide something useful here
) );
}
add_action( ‘woocommerce_product_options_inventory_product_data’, ‘action_woocommerce_product_options_inventory_product_data’, 10, 0 );

// Save Field
function action_woocommerce_admin_process_product_object( $product ) {
// Isset, yes or no
$checkbox = isset( $_POST[‘_prevent_add_to_cart_button’] ) ? ‘yes’ : ‘no’;

// Update meta
$product->update_meta_data( ‘_prevent_add_to_cart_button’, $checkbox );
}
add_action( ‘woocommerce_admin_process_product_object’, ‘action_woocommerce_admin_process_product_object’, 10, 1 );[/php]

To disable the add to cart button for simple and variable products, use:

[php]// Is_purchasable (simple)
function filter_woocommerce_is_purchasable( $purchasable, $product ) {
// Get meta
$hide_add_to_cart_button = $product->get_meta( ‘_prevent_add_to_cart_button’ );

// Compare
if ( $hide_add_to_cart_button == ‘yes’ ) {
$purchasable = false;
}

return $purchasable;
}
add_filter( ‘woocommerce_is_purchasable’, ‘filter_woocommerce_is_purchasable’, 10, 2 );

// Is_purchasable (variable)
function filter_woocommerce_variation_is_purchasable( $purchasable, $product ) {
$hide_add_to_cart_button = get_post_meta( $product->get_parent_id(), ‘_prevent_add_to_cart_button’, true );

// Compare
if ( $hide_add_to_cart_button == ‘yes’ ) {
$purchasable = false;
}

return $purchasable;
}
add_filter( ‘woocommerce_variation_is_purchasable’, ‘filter_woocommerce_variation_is_purchasable’, 10, 2 );[/php]

Note: There are several ways to disable/remove the add to cart button, so it depends on whether you want to hide or disable the button completely.

Leave a Comment