【问题标题】:Save and display product custom meta on WooCommerce orders and emails在 WooCommerce 订单和电子邮件中保存并显示产品自定义元数据
【发布时间】:2020-11-11 11:58:16
【问题描述】:

好的,所以基本上我们在 WooCommerce 商店中使用 ACF 创建了一个自定义字段,以便为特定产品添加“发货延迟”通知。

这是我们取得的成果的演示:https://www.safe-company.com/shop/machines/uvc-disinfection-lamp/

Single Product Page Reference Image

然后我们设法使用 Elementor(页面构建器)将此通知放在单个产品页面中,然后将此信息添加到购物车和结帐页面中的商品数据中,并将以下代码添加到我们的 functions.php 中

// Render the custom product field in cart and checkout
add_filter( 'woocommerce_get_item_data', 'wc_add_shipping_delay', 10, 2 );
function wc_add_shipping_delay( $cart_data, $cart_item ) 
{
    $custom_items = array();

    if( !empty( $cart_data ) )
        $custom_items = $cart_data;

    // Get the product ID
    $product_id = $cart_item['product_id'];

    if( $custom_field_value = get_post_meta( $product_id, 'shipping_delay_for_out_of_stock_items', true ) )
        $custom_items[] = array(
            'name'      => __( 'Shipping Delay', 'woocommerce' ),
            'value'     => $custom_field_value,
            'display'   => $custom_field_value,
        );

    return $custom_items;
}

Custom Field in Item Meta from Cart Page

我们现在的问题是,我们需要在电子邮件(分别显示在包含此数据的每个项目下方)和订单页面上添加此发货延迟通知。那怎么可能呢?由于我已经检查了一堆线程,但所有线程都是使用动态字段完成的(用户在购买时完成),但我们的案例场景完全不同。

请帮忙!!

【问题讨论】:

    标签: php wordpress woocommerce orders email-notifications


    【解决方案1】:

    以下内容会将您的自定义字段保存为订单商品元数据并在任何地方显示:

    // Save and display "shipping delay" on order items everywhere
    add_filter( 'woocommerce_checkout_create_order_line_item', 'action_wc_checkout_create_order_line_item', 10, 4 );
    function action_wc_checkout_create_order_line_item( $item, $cart_item_key, $values, $order ) {
    
        // Get the shipping delay
        $value = $values['data']->get_meta( 'shipping_delay_for_out_of_stock_items' );
    
        if( ! empty( $value ) ) {
            // Save it and display it
            $item->update_meta_data( __( 'Shipping Delay', 'woocommerce' ), $value );
        }
    }   
    

    代码在您的活动子主题(或活动主题)的functions.php 文件中。经过测试并且可以工作。

    【讨论】:

    • 非常感谢!这正是我们所需要的。祝你有美好的一天!
    • 完成!谢谢
    猜你喜欢
    • 2018-07-11
    • 2020-12-29
    • 2019-05-10
    • 2021-02-10
    • 2018-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-09
    相关资源
    最近更新 更多