Use woocommerce add to cart validation filter to prevent/stop duplicate of product meta values in wordpress database

Viewed 17

I have a digital product with a custom addon/ option (number field). Users can insert serial numbers in this field like 562788 then click checkout button. However, this number must be unique and one number should not be used more than once. To achieve this, am trying to use the woocommerce_add_to_cart_validation to check if the value provided by user already exists under the same meta key in wordpress. If exists, the add to cart/checkout action should return false with an error "Invalid Serial". I have tried this but for some reason the code below just can't work. It returns false every time.

Since when this field is submitted it is stored in the order object, am trying to look up and compare in a specific post type "shop_orders". I know this is nothing Stackoverflow community can't handle. Don't mind if my code misses some semicolons or brackets, I just edited it here.


add_filter( 'woocommerce_add_to_cart_validation', 'add_to_cart_validation', 10, 5 );

function add_to_cart_validation( $passed, $product_id, $quantity, $variation_id = null, $variations = null) {


//perform this action only for specific product
    global $product;
   
    if ($product->id == 19295){
//get the custom product option
$payoneer= sanitize_text_field( $_POST['payoneer_code'] );
//get posts and look up
global $post;
$args = array(
 'post_type'         => 'shop_order',  
//'post_type' => 'post',
'post_status'    => 'wc-processing',
   'meta_query' => array(
       array(
           'key' => 'payoneer_code',
           'value' => $payoneer 
       )
   ),
   'fields' => 'ids'
 );
 // perform the query
 $payo_query = new WP_Query( $args );

 $payo_ids = $payo_query->posts;

 // do something if the meta-key-value-pair exists in another order post
 if ( ! empty( $payo_ids ) ) {
     // do your stuff
 wc_add_notice( sprintf( __( "Invalid Code", "woocommerce" ) ) ,'error' );  
      return false;

return true;
 }else{

      return true;
}
}   

0 Answers
Related