从 WooCommerce 订单上的产品属性保存自定义交货日期 [英] Save custom delivery date from product attribute on WooCommerce order

查看:60
本文介绍了从 WooCommerce 订单上的产品属性保存自定义交货日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义属性,其中产品有不同的取货时间.我想将此日期作为自定义字段添加到我的 wc 订单中,以通过 cronjob 通知我的客户订单已准备好取货.

i have a custom attribute where products have different pickup times. i want to add this dates as a custom field to my wc orders, to notify my customers via cronjob that the order is ready to pickup.

使用下面的代码我得到了错误的日期,谁能告诉我这里出了什么问题?

with the code below i get the wrong date, can anyone tell me what is wrong here?

foreach ( $order->get_items() as $item_id => $item ) {
    $product_id = $item->get_product_id();
    $order_id = $order->get_id();
    $new_product = new WC_Product( $product_id );  // create an object of WC_Product class

    //$product_attribut = $new_product->get_attribute( 'pa_lieferfrequenz' );  // call get_attribute method
    $product_attribut = '1week';
    $date = date('d-m-Y', strtotime("+ ' . $product_attribut . '"));
    add_post_meta( $order_id, 'lwb_pickup_time_email_notification', $date );
}

推荐答案

最好在这个自定义挂钩函数中循环购物车项目并保存日期,一旦下订单就可以保存数据:

It's better to loop through cart items and save the date in this custom hooked function, once order is placed before saving data:

add_action( 'woocommerce_checkout_create_order', 'wc_checkout_create_order_action_callback' );
function wc_checkout_create_order_action_callback( $order ) {
    // Loop through cart items
    foreach ( WC()->cart->get_cart() as $cart_item ) {
        $lieferfrequenz = $cart_item['data']->get_attribute( 'pa_lieferfrequenz' );
        
        if ( ! empty( $lieferfrequenz ) ) {
            // Save the date as custom order meta data
            $order->update_meta_data( 'lwb_pickup_time_email_notification', date('d-m-Y', strtotime("+ '.$lieferfrequenz.'") ) );
            break; /// stop the loop
        }
    }
}

代码位于活动子主题(或活动主题)的 functions.php 文件中.它应该有效.

Code goes in functions.php file of your active child theme (or active theme). It should works.

但是如果订单中有许多不同的购物车项目,您应该重新考虑不同的事情,因为此代码将采用第一个购物车项目交货日期(或最后一个,如果您删除 break;).

But if there is many different cart items on an order, you should re-think things differently, as this code will take the first cart item delivery date (or the last one, if you remove break;).

相关: 在 WooCommerce 3 中获取订单项和 WC_Order_Item_Product

这篇关于从 WooCommerce 订单上的产品属性保存自定义交货日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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