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?
My Answer:
Yes, you can add a filter and function within an if statement in WordPress. In your case, you can add the filter within the if statement where you check if the order contains an item from a specific category. Here's how you can modify your code to achieve this:
php
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 ) {
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;
}
By adding the `add_filter` function within the if statement, the `change_woocommerce_order_number` function will only be called if the order contains an item from the specific category. This way, you can add a prefix to the order number based on the condition you have specified.
Rate this post
3 of 5 based on 2934 votesComments