在WooCommerce结帐页面上显示自定义字段产品信息

时间:2019-10-27 10:22:52

标签: php wordpress woocommerce product checkout

我正在尝试在结帐页面上显示多个自定义产品字段。我发现以下代码可用于一个自定义字段,但是如何向其中添加多个自定义字段?

add_filter( 'woocommerce_get_item_data', 'display_custom_product_field_data', 10, 2 );
function display_custom_product_field_data( $cart_data, $cart_item ) {

    // Define HERE your product custom field meta key  <==   <==   <==   <==   <==
    $meta_key = 'custom_time';

    $product_id = $cart_item['product_id'];

    $meta_value = get_post_meta( $product_id, $meta_key, true );

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

    if( !empty($meta_value) ) {
        $custom_items[] = array(
            'key'       => __('Time', 'woocommerce'),
            'value'     => $meta_value,
            'display'   => $meta_value,
        );
    }
    return $custom_items;
}

1 个答案:

答案 0 :(得分:0)

您可以将$ meta_keys定义为数组

$meta_keys = array('custom_time','custom_time2'); // or more than tow 

和其他字段

$ dictionary = array('custom_time'=>'Time','custom_time2'=>'Date')

$product_id = $cart_item['product_id'];

foreach($meta_keys as $key=>$meta_key){

$meta_value = get_post_meta( $product_id, $meta_key, true );

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

if( !empty($meta_value) ) {
    $custom_items[] = array(
        'key'       => __( $dictionary[$meta_key] , 'woocommerce'), //or user $meta_key
        'value'     => $meta_value,
        'display'   => $meta_value,
    );
}
}
return $custom_items;