1
votes

In Woocommerce, I successfully added a custom field for product variations within the backend. Saving its input data and displaying it within the add-to-cart/variation.php works as well.

But what about displaying the value of this field within the cart.php?

I only found solutions of this for regular product items but not for product variations. Here's what I have so far within my functions.php file:

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

1 Answers

1
votes

To display this custom field in cart items, use the following:

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

It will work as well inall products post type and Product variations too in cart and checkout pages.

Code goes in function.php file of your active child theme (or theme). Tested and works.