在Woocommerce购物车上显示产品变体的自定义字段

时间:2018-03-19 20:52:41

标签: php woocommerce cart product variations

在Woocommerce中,我成功为后端内的产品变体添加了自定义字段。保存其输入数据并在add-to-cart/variation.php内显示它。

但是如果在cart.php中显示此字段的值呢?

我只为常规产品找到了解决方案,但没有找到产品差异的解决方案。这是我目前在functions.php文件中的内容:

//Display Fields in admin on product edit screen
add_action( 'woocommerce_product_after_variable_attributes', 'woo_variable_fields', 10, 3 );

//Save variation fields values
add_action( 'woocommerce_save_product_variation', 'save_variation_fields', 10, 2 );

// Create new fields for variations
function woo_variable_fields( $loop, $variation_data, $variation ) {

echo '<div class="variation-custom-fields">';

  // Text Field
  woocommerce_wp_text_input( 
    array( 
      'id'          => '_text_field['. $loop .']', 
      'label'       => __( 'additional fees (e.g. monthly fee)', 'woocommerce' ), 
      'placeholder' => '',
      //'desc_tip'    => true,
      'wrapper_class' => 'form-row form-row-first',
      //'description' => __( 'Enter the custom value here.', 'woocommerce' ),
      'value'       => get_post_meta($variation->ID, '_text_field', true)
    )
  );

echo "</div>"; 

}

/** Save new fields for variations */
function save_variation_fields( $variation_id, $i) {

// Text Field
$text_field = stripslashes( $_POST['_text_field'][$i] );
update_post_meta( $variation_id, '_text_field', esc_attr( $text_field ) );
}

// Custom Product Variation
add_filter( 'woocommerce_available_variation', 'custom_load_variation_settings_products_fields' );

function custom_load_variation_settings_products_fields( $variations )    { 
$variations['variation_custom_field'] = get_post_meta( $variations[ 'variation_id' ], '_text_field', true );  
return $variations;
}

1 个答案:

答案 0 :(得分:1)

要在购物车商品中显示此自定义字段,请使用以下内容:

add_filter( 'woocommerce_get_item_data', 'display_custom_field_as_item_data', 20, 2 );
function display_custom_field_as_item_data( $cart_data, $cart_item ) {
    if( $value = get_post_meta( $cart_item['data']->get_id(), '_text_field', true ) ){
        $cart_data[] = array(
            'name' => __( 'Additional Monthly Fee', 'woocommerce' ),
            'value' => sanitize_text_field( $value )
        );
    }
    return $cart_data;
}

在购物车和结帐页面中,它也适用于所有产品的邮寄类型和产品变体。

代码放在活动子主题(或主题)的function.php文件中。经过测试和工作。