【问题标题】:Adding prefix to WooCommerce order number if order has items from a specific product category如果订单包含来自特定产品类别的商品,则为 WooCommerce 订单号添加前缀
【发布时间】:2021-03-23 07:24:12
【问题描述】:

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

为此,我编写了以下代码:

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,现在我需要运行以下函数:

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 语句中添加过滤器和函数吗?

【问题讨论】:

    标签: php wordpress woocommerce orders prefix


    【解决方案1】:

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

    因此,当订单包含来自特定类别的商品时,要在订单号上添加前缀,您只需使用:

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

    相关:Adding prefix to WooCommerce order number based on multiple categories

    【讨论】:

      猜你喜欢
      • 2018-09-23
      • 2019-08-29
      • 2021-04-30
      • 2019-01-26
      • 1970-01-01
      • 2015-07-16
      • 1970-01-01
      • 2013-04-20
      • 2015-08-14
      相关资源
      最近更新 更多