I'm trying to disable adding to cart certain products which have the "Call to Order" checkbox ticked (see code below) on the product editor.
add_action( 'woocommerce_product_options_general_product_data', 'custom_general_product_data_custom_fields' );
/**
* Add `Call to Order` field in the Product data's General tab.
*/
function custom_general_product_data_custom_fields() {
// Checkbox.
woocommerce_wp_checkbox(
array(
'id' => '_not_ready_to_sell',
'wrapper_class' => 'show_if_simple',
'label' => __( 'Call to Order', 'woocommerce' ),
'description' => __( '', 'woocommerce' )
)
);
}
add_action( 'woocommerce_process_product_meta', 'custom_save_general_proddata_custom_fields' );
/**
* Save the data values from the custom fields.
* @param int $post_id ID of the current product.
*/
function custom_save_general_proddata_custom_fields( $post_id ) {
// Checkbox.
$woocommerce_checkbox = isset( $_POST['_not_ready_to_sell'] ) ? 'yes' : 'no';
update_post_meta( $post_id, '_not_ready_to_sell', $woocommerce_checkbox );
}
add_filter( 'woocommerce_is_purchasable', 'custom_woocommerce_set_purchasable', 10, 2);
/**
* Mark "Not ready to sell" products as not purchasable.
*/
function custom_woocommerce_set_purchasable() {
$not_ready_to_sell = get_post_meta( get_the_ID(), '_not_ready_to_sell' , true);
return ( 'yes' == $not_ready_to_sell ? false : true );
}
add_filter( 'woocommerce_product_add_to_cart_text', 'custom_product_add_to_cart_text' );
/**
* Change "Read More" button text for non-purchasable products.
*/
function custom_product_add_to_cart_text() {
$not_ready_to_sell = get_post_meta( get_the_ID(), '_not_ready_to_sell', true );
if ( 'yes' === $not_ready_to_sell ) {
return __( 'Call to Order', 'woocommerce' );
} else {
return __( 'Add to Cart', 'woocommerce' );
}
}
The products that have the checkbox ticked, are in fact not purchasable, which is the desired outcome.
The problem I'm having is when I click "Add to Cart" for purchasable products (those without the checkbox ticked) on the product catalog page, I am redirected to the product page and a default WooCommerce message "Sorry, this product cannot be purchased." appears. What should be happening is that when the "Add to Cart" button is clicked, the product is automatically added to the cart.
Also from the single product page, I can add the purchasable cart without a problem.
I am not sure why this is happening this way. Any ideas?
I have tested your code and it work without problems… I don't have the problematic behavior you describe… So something else is making trouble:
You will need first to make a database backup… Then you should try to:
The problem could come from the theme too.
Now since Woocommerce 3 and introduced CRUD Objects, your code is a bit outdated.
Here is revisited and enhanced code version (for Woocommerce 3+):
Code goes on function.php file of your active child theme (or active theme). It could works.