1

I need to remove checkout page field validation if a particular product is in the cart.

Plugin code :

add_action('woocommerce_checkout_process', 'my_custom_checkout_field_process');

function my_custom_checkout_field_process() {
    // Check if set, if its not set add an error.
    if ( ! $_POST['developer_name'] )
        wc_add_notice( __( 'Please fill in your name.' ), 'error' );
}

I need to remove this action hook my_custom_checkout_field_process only if the customer added the product_id (19) to the cart. Else there's no need to remove the add_action.

closed as off-topic by Jacob Peattie, rudtek, Mayeenul Islam, Howdy_McGee Apr 4 at 14:23

This question appears to be off-topic. The users who voted to close gave this specific reason:

If this question can be reworded to fit the rules in the help center, please edit the question.

2

try this below code in your function.php file or in your plugin

add_action("init", function () {
    // removing the woocommerce hook
    foreach( WC()->cart->get_cart() as $cart_item ){
            $product_id = $cart_item['product_id'];
            if($product_id!='19')
            {
        remove_action('woocommerce_checkout_process', 'my_custom_checkout_field_process');
    }
}
});
  • thanks man it's working – Kanewilliam Apr 8 at 7:50
0

WordPress compiles a list of actions quite early in the process, possibly before the product_id is known. So you probably (I don't know where WooCommerce executes this action) cannot execute this action conditionally.

However, what you can do is remove the action completely and define a new action that includes the condition. Also you must make sure this is done before the old action is executed. Like this:

add_action ('woocommerce_checkout_process', 'wpse333234_change_hook', 1); // early priority

function wpse333234_change_hook () {
  remove_action ('woocommerce_checkout_process', 'my_custom_checkout_field_process'); // remove old hooked function
  add_action ('woocommerce_checkout_process', 'wpse333234_new_hook', 10); // define new hooked function with later priority
  }

function wpse333234_new_hook () {
  // Check if set, if its not set add an error.
  if ( ! $_POST['developer_name'] && !$product_id==19)
    wc_add_notice( __( 'Please fill in your name.' ), 'error' );
    }

Beware that the latter function will give an error initially, because $product_id is not defined in the function. I don't know how this is defined in WooCommerce. You'll need a way to access this (global?) variable in some way.

  • @cjbi Thanks for reply. but it's not working.. – Kanewilliam Apr 2 at 15:22
  • Which part is not working? – cjbj Apr 2 at 19:00
  • It's not removed the validation. – Kanewilliam Apr 3 at 6:25

Not the answer you're looking for? Browse other questions tagged or ask your own question.