Customer paid once, but sometimes items shows twice in the order, it happen randomly. Usually twice a week.
In this case, I need a function to change order's status when that happens (like when an order have at least duplicated items names).
Here is my code attempt:
add_filter( 'woocommerce_cod_process_payment_order_status', 'prefix_filter_wc_complete_order_status', 10, 3 );
add_filter( 'woocommerce_payment_complete_order_status', 'prefix_filter_wc_complete_order_status', 10, 3 );
function prefix_filter_wc_complete_order_status( $status, $order_id, $order ) {
if( ! $order_id ) return;
$order = wc_get_order( $order_id );
$all_products_id = array();
foreach ($order->get_items() as $item_key => $item ){
$item_name = $item->get_name();
$all_products_id[] = $item_name;
}
$o_num = count($all_products_id);
if($o_num == 1){
return 'processing';
}else{
$standard = 0;
for($i=1;$i<$o_num;$i++){
if($all_products_id[0] == $all_products_id[i]){
$standard++;
}
}
if($standard > 0){
return 'on-hold';
}else{
return 'processing';
}
}
when I test it, I get this error: SyntaxError: Unexpected token < in JSON at position 18
Any suggestions will be appreciated.
There are some mistakes and complications in your code. Also you can't use both hooks with the same function as they don't have the same arguments.
What you can do is to use a custom conditional function inside separated functions for each hook this way:
// Custom conditional function
function has_duplicated_items( $order ) {
$order_items = $order->get_items();
$items_count = (int) count($order_items);
if ( $items_count === 1 ) {
return false;
}
$items_names = array();
// Loop through order items
foreach( $order_items as $tem_id => $item ){
$product_id = $item->get_variation_id() > 0 ? $item->get_variation_id() : $item->get_product_id();
$items_names[$product_id] = $item->get_name();
}
return absint(count($items_names)) !== $items_count ? true : false;
}
add_filter( 'woocommerce_cod_process_payment_order_status', 'filter_wc_cod_process_payment_order_status', 10, 2 );
function filter_wc_cod_process_payment_order_status( $status, $order ) {
return has_duplicated_items( $order ) ? 'on-hold' : 'processing';
}
add_filter( 'woocommerce_payment_complete_order_status', 'filter_wc_payment_complete_order_status', 10, 3 );
function filter_wc_payment_complete_order_status( $status, $order_id, $order ) {
return has_duplicated_items( $order ) ? 'on-hold' : 'processing';
}
This time this should solve the error: "SyntaxError: Unexpected token < in JSON at position 18"
Code goes in function.php file of your active child theme (or active theme). It should works.