如果订单包含来自特定产品类别的商品,则为 WooCommerce 订单号添加前缀 [英] Adding prefix to WooCommerce order number if order has items from a specific product category

查看:134
本文介绍了如果订单包含来自特定产品类别的商品,则为 WooCommerce 订单号添加前缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在购物车中只能有一件商品的网店中,当订单包含来自特定类别的商品时,我需要在订单号前添加前缀

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*
}

}


如果$category_in_order,现在我需要以下函数来运行:


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;
}

但我似乎无法找到.我可以在 if 语句中添加过滤器和函数吗?

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

推荐答案

在 if 条件中不需要使用过滤器钩子.您可以立即将所有逻辑添加到正确的过滤器挂钩中.

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 );


相关:基于多个类别为 WooCommerce 订单号添加前缀

这篇关于如果订单包含来自特定产品类别的商品,则为 WooCommerce 订单号添加前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆