Search code examples
phpwordpresswoocommerceordersprefix

Adding prefix to WooCommerce order number if order has items from a specific product category


In a webshop that can only have one item in the cart, I need to add a prefix to the order number when the order contains an item from a specific category

For this I wrote the following code:

add_action( 'woocommerce_prefix', 'check_product_category_in_order', 5 );
 
function check_product_category_in_order( $order_id ) { 
 
if ( ! $order_id ) {
    return;
}
 
$order = wc_get_order( $order_id );

$category_in_order = false;

$items = $order->get_items(); 
    
foreach ( $items as $item ) {      
    $product_id = $item['product_id'];  
    if ( has_term( 'MY-PRODUCT-CATEGORY', 'product_cat', $product_id ) ) {
        $category_in_order = true;
        break;
    }
}
 
   
if ( $category_in_order ) {
    
   *New funtion here*
}

}

Now I need the following function to run if $category_in_order:

add_filter( 'woocommerce_order_number', 'change_woocommerce_order_number' );

function change_woocommerce_order_number( $order_id ) {

    $prefix = 'AB-';
    $new_order_id = $prefix . $order_id;
    return $new_order_id;
}

But I cant seem to find out. Can I add a filter and function whitin an if statement?


Solution

  • There is no need to use a filter hook in the if condition. You can immediately add all logic in the correct filter hook.

    So to add a prefix to the order number when the order contains an item from a specific category you only have to use:

    function filter_woocommerce_order_number( $order_id, $order ) {
        // Prefix
        $prefix = 'AB-';
        
        // Specific categories: the term name/term_id/slug. Several could be added, separated by a comma
        $categories = array( 'categorie-1', 'categorie-2', 15, 16 );
        
        // Flag
        $found = false;
        
        // Loop through order items
        foreach ( $order->get_items() as $item ) {
            // Product ID
            $product_id = $item->get_variation_id() > 0 ? $item->get_variation_id() : $item->get_product_id();
    
            // Has term (product category)
            if ( has_term( $categories, 'product_cat', $product_id ) ) {
                $found = true;
                break;
            }
        }
        
        // true
        if ( $found ) {
            $order_number = $prefix . $order_id;
        } else {
            $order_number = $order_id;
        }
        
        return $order_number;
    }
    add_filter( 'woocommerce_order_number', 'filter_woocommerce_order_number', 10, 2 );
    

    Related: Adding prefix to WooCommerce order number based on multiple categories