Save custom delivery date from product attribute on WooCommerce order

半世苍凉 提交于 2020-07-16 05:46:08

问题


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

回答1:


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

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

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

Related: Get Order items and WC_Order_Item_Product in WooCommerce 3



来源:https://stackoverflow.com/questions/62882495/save-custom-delivery-date-from-product-attribute-on-woocommerce-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!