首页 文章

处理后,在订单中显示产品自定义字段值

提问于
浏览
2

在woocommerce上,我使用下面的代码来渲染一些产品自定义字段,在购物车和结帐时:

add_filter( 'woocommerce_get_item_data', 'rendering_meta_field_on_cart_and_checkout', 10, 2 );

function rendering_meta_field_on_cart_and_checkout( $cart_data, $cart_item ) {
    $custom_items = array();

    if( !empty( $cart_data ) ) {
        $custom_items = $cart_data;
    }
    if( isset( $cart_item['wccpf_enter_product_id'] ) ) {

        $diamond = $cart_item['wccpf_enter_product_id'];

        $pacolor = get_the_terms($diamond, 'pa_color');
        foreach ( $pacolor  as $pacolor  ) {
           $color= $pacolor ->name;
        }


        $custom_items[] = array( "name" => "color", "value" => $color);
    }
    return $custom_items;
}

如何在订单中显示自定义产品字段wccpf_enter_product_id'的值?

谢谢 .

1 回答

  • 4

    您可以使用挂钩在woocommerce_add_order_item_meta动作钩子中的自定义函数来实现此目的 .

    首先需要在产品中添加一个属性,以便为自定义字段值获取“可读的干净标签”,该字段值将显示为订单商品元数据 . 为此,您必须先创建一个属性,然后在产品中设置任何值(因为您将在下面的代码中替换此值) . 请参阅此处有关该流程的更多说明......您必须在我的代码中使用您在wp_woocommerce_order_itemmeta MySQL表中找到的特定自定义密钥替换'custom_field_key',以获取特定订单ID的相应项ID . 要查找订单的相应商品ID,您可以使用订单ID在wp_woocommerce_order_items MySQL表中进行搜索...您还必须设置正确的属性slug而不是'pa_your_attribute',以在订单中显示此自定义字段的正确标签文本值 . (见下面其他类似的答案参考) .

    所以你的代码将是这样的:

    // ADD THE INFORMATION AS META DATA SO THAT IT CAN BE SEEN AS PART OF THE ORDER
    add_action('woocommerce_add_order_item_meta','add_and_update_values_to_order_item_meta', 1, 3 );
    function add_and_update_values_to_order_item_meta( $item_id, $item_values, $item_key ) {
    
        // Getting your custom product ID value from order item meta
        $custom_value = wc_get_order_item_meta( $item_id, 'custom_field_key', true );
    
        // Here you update the attribute value set in your simple product
        wc_update_order_item_meta( $item_id, 'pa_your_attribute', $custom_value );
        }
    }
    

    代码放在活动子主题(或主题)的function.php文件中,或者放在任何插件文件中 .

    这应该工作


    Related answers:

相关问题