Override woocommerce cart item price with product custom field value - php

In woocommerce I am using Advanced Custom Fields and trying to get a custom field value in each product as price instead of the default product price. this custom field is called 'custom_price'.
How can I change this hard coded value to use that instead?
Here is my code:
add_action( 'woocommerce_before_calculate_totals', 'add_custom_price'
);
function add_custom_price( $cart_object ) {
$custom_price = 10;
foreach ( $cart_object->cart_contents as $key => $value ) {
$value['data']->set_price($custom_price);
}
}

Update 3: Here is the complete solution with all custom fields and the cart item price change.
You will need to add some jQuery code to make your product price calculation, display calculated price on product page and set this calculated price on a hidden field.
Once product will be added to cart, the code will catch the calculated price and will set it in the corresponding cart item…
The code:
// The product custom field - Frontend
add_action( 'woocommerce_before_add_to_cart_button', 'custom_discount_price_product_field' );
function custom_discount_price_product_field() {
global $product;
$curs = get_woocommerce_currency_symbol(); // Currency symbol
// Get the discounted value (from product backend)
$discount = (float) get_post_meta( $product->get_id(), '_price_discount', true );
// jQuery will get the discount here for calculations
echo '<input type="hidden" name="price_discount" value="'.$discount.'">';
echo '<div>';
woocommerce_form_field( 'select_price', array(
'type' => 'select',
'class' => array('my-field-class form-row-wide'),
'label' => __('Discount'),
'options' => array(
'' => __( 'Select your discount', 'woocommerce' ),
'5' => $curs . '5',
'10' => $curs . '10',
'15' => $curs . '15',
'20' => $curs . '20',
),
), '' );
// This field will be used to send the calculated price
// jQuery will set the calculated price on this field
echo '<input type="hidden" name="custom_price" value="52">'; // 52 is a fake value for testing purpose
echo '</div><br>';
// BELOW your jquery code to calculate price and update "custom_price" hidden field
?>
<script type="text/javascript">
jQuery( function($){
// Here
});
</script>
<?php
}
// Add a custom field to product in backend
add_action( 'woocommerce_product_options_pricing', 'add_field_product_options_pricing' );
function add_field_product_options_pricing() {
global $post;
echo '<div class="options_group">';
woocommerce_wp_text_input( array(
'id' => '_price_discount',
'label' => __('Discount price', 'woocommerce') . ' (%)',
'placeholder' => __('Set the Discount price…', 'woocommerce'),
'description' => __('Enter the custom value here.', 'woocommerce'),
'desc_tip' => 'true',
));
echo '</div>';
}
// Save product custom field to database when submitted in Backend
add_action( 'woocommerce_process_product_meta', 'save_product_options_custom_fields', 30, 1 );
function save_product_options_custom_fields( $post_id ){
// Saving custom field value
if( isset( $_POST['_price_discount'] ) ){
update_post_meta( $post_id, '_price_discount', sanitize_text_field( $_POST['_price_discount'] ) );
}
}
// Add custom calculated price conditionally as custom data to cart items
add_filter( 'woocommerce_add_cart_item_data', 'add_custom_price_to_cart_item_data', 20, 2 );
function add_custom_price_to_cart_item_data( $cart_item_data, $product_id ){
if( ! isset($_POST['custom_price']) )
return $cart_item_data;
$cart_item_data['custom_price'] = (float) sanitize_text_field( $_POST['custom_price'] );
$cart_item_data['unique_key'] = md5( microtime() . rand() ); // Make each item unique
return $cart_item_data;
}
// Set conditionally a custom item price
add_action('woocommerce_before_calculate_totals', 'set_cutom_cart_item_price', 20, 1);
function set_cutom_cart_item_price( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
foreach ( $cart->get_cart() as $cart_item ) {
if ( isset( $cart_item['custom_price'] ) )
$cart_item['data']->set_price( $cart_item['custom_price'] );
}
}
Code goes in function.php file of your active child theme (or active theme). Tested and works (but you will need to make your own calculations with jquery)

Related

How can I make the max-price (of my price range) appear on woocommerce cart, checkout and order notice pages?

please I have this code which I used to add max price to my woocommerce store.
as show here
But I'm seeking for a way to make the max-price appear on the cart, checkout, and order notice pages together with the regular price.
Here is the code I used.
// Add a custom field for price range to product in backend
add_action( 'woocommerce_product_options_pricing', 'add_field_product_options_pricing' );
function add_field_product_options_pricing() {
global $post;
echo '<div class="options_group show_if_simple">';
woocommerce_wp_text_input( array(
'id' => '_max_price_for_range',
'label' => __('Max price for range', 'woocommerce').' ('.get_woocommerce_currency_symbol().')',
'placeholder' => __('Set the max price for range', 'woocommerce'),
'description' => __('Set the max price for range, to activate it…', 'woocommerce'),
'desc_tip' => 'true',
));
echo '</div>';
}
// Save product custom field to database when submitted in Backend
add_action( 'woocommerce_process_product_meta', 'save_product_options_custom_fields', 30, 1 );
function save_product_options_custom_fields( $post_id ){
// Saving custom field value
if( isset( $_POST['_max_price_for_range'] ) ){
update_post_meta( $post_id, '_max_price_for_range', sanitize_text_field( $_POST['_max_price_for_range'] ) );
}
}
// Frontend: display a price range when the max price is set for the product
add_filter( 'woocommerce_get_price_html', 'custom_range_price_format', 10, 2 );
function custom_range_price_format( $price, $product ) {
// Only for simple product type
if( $product->is_type('simple') ){
// Get the max price for range
$max_price = get_post_meta( $product->get_id(), '_max_price_for_range', true );
if( empty($max_price) )
return $price; // exit
$active_price = wc_get_price_to_display( $product, array( 'price' => $product->get_price() ) );
$price = sprintf( '%s – %s', wc_price($active_price), wc_price($max_price) );
}
return $price;
}
I'm really new to PHP coding so I wasn't able to pick the right hooks to add the max price to the pages.
Thanks in anticipation of your help.

Save Custom Field Data to Cart and Order of a Woocommerce product variation

We managed to put a custom field for variation products following Remi Corson guide here
At this point, we are able to show the custom text field in the single product page when users select the variation, but this is not enough in the purchase process since we need to:
A) Display this text in Cart and Checkout
B) Save this information so it shows in Thank You Page, Emails and Admin Order Edit Page
Something similar to Save and display product custom meta on WooCommerce orders and emails, but with product variations instead of simple products.
This is the code we added to our functions.php to add the custom field to the product variations
// Add Variation Settings
add_action( 'woocommerce_product_after_variable_attributes', 'variation_settings_fields', 10, 3 );
// Save Variation Settings
add_action( 'woocommerce_save_product_variation', 'save_variation_settings_fields', 10, 2 );
/**
* Create new fields for variations
*
*/
function variation_settings_fields( $loop, $variation_data, $variation ) {
// Text Field
woocommerce_wp_text_input(
array(
'id' => '_text_field[' . $variation->ID . ']',
'label' => __( 'My Text Field', 'woocommerce' ),
'placeholder' => 'http://',
'desc_tip' => 'true',
'description' => __( 'Enter the custom value here.', 'woocommerce' ),
'value' => get_post_meta( $variation->ID, '_text_field', true )
)
);
// Hidden field
woocommerce_wp_hidden_input(
array(
'id' => '_hidden_field[' . $variation->ID . ']',
'value' => 'hidden_value'
)
);
}
/**
* Save new fields for variations
*
*/
function save_variation_settings_fields( $post_id ) {
// Text Field
$text_field = $_POST['_text_field'][ $post_id ];
if( ! empty( $text_field ) ) {
update_post_meta( $post_id, '_text_field', esc_attr( $text_field ) );
}
// Hidden field
$hidden = $_POST['_hidden_field'][ $post_id ];
if( ! empty( $hidden ) ) {
update_post_meta( $post_id, '_hidden_field', esc_attr( $hidden ) );
}
}
// Add New Variation Settings
add_filter( 'woocommerce_available_variation', 'load_variation_settings_fields' );
/**
* Add custom fields for variations
*
*/
function load_variation_settings_fields( $variations ) {
// duplicate the line for each field
$variations['text_field'] = get_post_meta( $variations[ 'variation_id' ], '_text_field', true );
return $variations;
}
So the goal here is how can we show this custom field for each variation in the Cart and Checkout below the items (Something like the image below - Look at the Shipping delay notice)
And to save that custom field info that each variation has to the Thank You Page, Emails and Order Page (We did it for simple products with this code, but this doesn't work for variable ones)
// Save and display "Custom Field for Simple Products" 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 Custom Field
$value = $values['data']->get_meta( 'custom_field_for_simple_products' );
if( ! empty( $value ) ) {
// Save it and display it
$item->update_meta_data( __( 'Custom Fields', 'woocommerce' ), $value );
}
}
Please help!!
Updated
There are some mistakes in your code… The following revisited code will solve your issue:
// Display Variation custom fields (admin)
add_action( 'woocommerce_product_after_variable_attributes', 'display_variation_setting_custom_fields', 10, 3 );
function display_variation_setting_custom_fields( $loop, $variation_data, $variation ) {
echo '<div>';
woocommerce_wp_text_input( array( // Text Field
'id' => "_text_field[$loop]",
'label' => __("My Text Field", "woocommerce"),
'placeholder' => "http://",
'desc_tip' => true,
'description' => __("Enter the custom value here.", "woocommerce"),
'wrapper_class' => 'form-row form-row-full',
'value' => get_post_meta( $variation->ID, '_text_field', true ),
) );
woocommerce_wp_hidden_input( array( // Hidden field
'id' => "_hidden_field[$loop]",
'value' => 'hidden_value',
) );
echo '</div>';
}
// Save Variation custom fields
add_action( 'woocommerce_save_product_variation', 'save_variation_custom_fields', 10, 2 );
function save_variation_custom_fields( $variation_id, $i ) {
// Save Text Field
if( isset( $_POST['_text_field'][$i] ) && ! empty( $_POST['_text_field'][$i] ) )
update_post_meta( $variation_id, '_text_field', sanitize_text_field( $_POST['_text_field'][$i] ) );
// Save Hidden Field
if( isset( $_POST['_hidden_field'][$i] ) && ! empty( $_POST['_hidden_field'][$i] ) )
update_post_meta( $variation_id, '_hidden_field', esc_attr( $_POST['_hidden_field'][$i] ) );
}
// Include our variation custom field
add_filter( 'woocommerce_available_variation', 'include_variation_custom_field', 10, 3) ;
function include_variation_custom_field( $data, $product, $variation ) {
$data['text_field'] = $variation->get_meta( '_text_field' );
return $data;
}
// Save and display "Custom Field for Simple Products" on order items everywhere
add_filter( 'woocommerce_checkout_create_order_line_item', 'action_wc_checkout_create_order_line_item_2', 10, 4 );
function action_wc_checkout_create_order_line_item_2( $item, $cart_item_key, $values, $order ) {
// Get the Custom Field
$value = $values['data']->get_meta( '_text_field' );
if( ! empty( $value ) ) {
// Save it and display it
$item->update_meta_data( __( 'Custom Field', 'woocommerce' ), $value );
}
}
Code goes in functions.php file of your active child theme (or active theme) . Tested and works.
Related: Save and display product custom meta on WooCommerce orders and emails
Somme screenshots
On admin product variations settings:
On order received page (thankyou):
On admin edit orders pages:

Calculate and show the new price after choosing the weight of the product in WooCommerce

In WooCommerce, I use a code that shows the steak weight selection form, saves the selection data and displays this data in the cart, on the checkout page, when editing the order and in email notifications.
// Display Custom Checkbox Field
add_action('woocommerce_product_options_general_product_data', 'steak_custom_field_add');
function steak_custom_field_add(){
global $post;
// Checkbox
woocommerce_wp_checkbox(
array(
'id' => '_steak_checkbox',
'label' => __('Steak Weight', 'woocommerce' ),
'description' => __( 'If necessary, enable steak weight selection', 'woocommerce' )
)
);
}
// Save Custom Checkbox Field
add_action('woocommerce_process_product_meta', 'steak_custom_field_save');
function steak_custom_field_save($post_id){
// Custom Product Checkbox Field
$steak_checkbox = isset( $_POST['_steak_checkbox'] ) ? 'yes' : 'no';
update_post_meta($post_id, '_steak_checkbox', esc_attr( $steak_checkbox ));
}
// Display Custom Select Box
add_action( 'woocommerce_before_add_to_cart_button', 'display_steak_custom_field', 0 );
function display_steak_custom_field() {
global $product;
// If is single product page and have the "steak_checkbox" enabled we display the field
if ( $product->get_meta( '_steak_checkbox' ) === 'yes' ) {
echo '<div class="steak_select_box">';
$select = woocommerce_form_field( 'steak_custom_options', array(
'type' => 'select',
'class' => array('my-steak-select-box form-row-wide'),
'label' => __('Steak Weight'),
'required' => false,
'return' => false,
'options' => array(
'' => 'Select...',
'300g' => '300g',
'400g' => '400g',
'500g' => '500g',
'600g' => '600g',
'700g' => '700g',
'800g' => '800g',
'900g' => '900g',
'1000g' => '1000g'
)
), '' );
echo $select;
echo '</div>';
}
}
// Add as custom cart item data
add_filter( 'woocommerce_add_cart_item_data', 'add_custom_steak_cart_item_data', 10, 21 );
function add_custom_steak_cart_item_data($cart_item_data, $product_id, $variation_id ){
if( isset( $_POST['steak_custom_options'] ) ) {
$cart_item_data['steak_option'] = wc_clean( $_POST['steak_custom_options'] );
}
return $cart_item_data;
}
// Add custom fields values under cart item name in cart
add_filter( 'woocommerce_cart_item_name', 'steak_custom_field_add_cart', 10, 21 );
function steak_custom_field_add_cart( $item_name, $cart_item, $cart_item_key ) {
if( ! is_cart() )
return $item_name;
if( isset($cart_item['steak_option']) ) {
$item_name .= '<div class="my-steak-class"><strong>' . __("Steak Weight", "woocommerce") . ':</strong> ' . $cart_item['steak_option'] . '</div>';
}
return $item_name;
}
// Display custom fields values under item name in checkout
add_filter( 'woocommerce_checkout_cart_item_quantity', 'steak_custom_checkout_cart_item_name', 10, 21 );
function steak_custom_checkout_cart_item_name( $item_qty, $cart_item, $cart_item_key ) {
if( isset($cart_item['steak_option']) ) {
$item_qty .= '<div class="my-steak-class"><strong>' . __("Steak Weight", "woocommerce") . ':</strong> ' . $cart_item['steak_option'] . 'гр.</div>';
}
return $item_qty;
}
// Save chosen select field value to each order item as custom meta data and display it everywhere
add_action('woocommerce_checkout_create_order_line_item', 'save_order_item_steak_field', 10, 21 );
function save_order_item_steak_field( $item, $cart_item_key, $values, $order ) {
if( isset($values['steak_option']) ) {
$key = __('Steak Weight', 'woocommerce');
$value = $values['steak_option'];
$item->update_meta_data( $key, $value ,$item->get_id());
}
}
add_action('wp_footer','add_footer_steak_script');
function add_footer_steak_script(){
?>
<script>
( function( $ ) {
$( document ).ready( function() {
$(document).on('change', '#steak_custom_options' ,function() {
$('.add_to_cart_button').data('steak_custom_options', this.value)
});
});
}( jQuery ) );
</script>
<?php
}
But unfortunately, I do not know how to solve one problem ...
The price of this product is calculated per 100 grams. The minimum order quantity is 300 grams. And I need that, when choosing the weight of the product, the final cost of this product should be calculated accordingly.
For example:
for 300g - $regular_price * 3 = $new_price
for 500g - $regular_price * 5 = $new_price
for 1000g - $regular_price * 10 = $new_price
etc.
The total cost of this product should be shown next to the main price per 100 grams.
I think this code will be useful to other developers as well. I will be very happy for your help!
To adjust the product price, on the cart page, etc.. based on the weight selected from the dropdown, add the following code
function my_before_calculate_totals( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// Loop through cart items
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
if( isset( $cart_item['steak_option'] ) ) {
// Remove the last 2 zeros (100g becomes 1, 300g becomes 3, 1000g becomes 10, etc...)
// Remove 'g' from grams
// convert string to integer
$chosen_weight = (int) str_replace( '00', '', str_replace('g', '', $cart_item['steak_option']) );
// Get current price
$current_price = $cart_item['data']->get_price();
// Set new price, price is already known per 100g
$cart_item['data']->set_price( $current_price * $chosen_weight );
}
}
}
add_action( 'woocommerce_before_calculate_totals', 'my_before_calculate_totals', 10, 1 );
To change the price on the single product page, based on the dropdown menu, add this
function add_footer_steak_script() {
global $woocommerce, $product;
?>
<script type="text/javascript">
jQuery(document).ready(function ($) {
console.log('JS works!');
var price = <?php echo $product->get_price(); ?>, currency = '<?php echo get_woocommerce_currency_symbol(); ?>';
$( '[name=steak_custom_options]' ).change(function(){
if (!(this.value < 1)) {
var dropdown_val = this.value;
var remove_g = dropdown_val.replace( 'g', '' );
var remove_double_zero = remove_g.replace( '00', '' );
var product_total = parseFloat( price * remove_double_zero );
$( '.woocommerce-Price-amount' ).html( currency + product_total.toFixed(2));
}
});
});
</script>
<?php
}
add_action('wp_footer','add_footer_steak_script');

Save custom metadata from subscription product variation to order

I need to be able to add admin data to subscription product variations (Woo Subscriptions extension) in order to pass this data on to fulfilment centres when an order is placed.
The issue I have is getting these values out from the product and passing them into the order and email notifications such that they can be properly exported, added to shipping labels and emailed via the various woo notifications.
I have custom meta fields added to variations on a subscription product. I can add data into these and they save data properly into the database on the correct variation ID. No problem there.
I can show custom test data on the cart and checkout page and also save this data into the order as you'll see in the code.
For brevity, the code is reduced below but there are in fact 6 text fields:
// Add custom field inputs to each product variation
add_action( 'woocommerce_variation_options_pricing', 'add_custom_field_to_variations', 10, 3 );
function add_custom_field_to_variations( $loop, $variation_data, $variation ) {
woocommerce_wp_text_input(
array(
'id' => '_dose_customer_field[' . $loop . ']',
'label' => __( 'Dose (Customer)', 'woocommerce' ),
'placeholder' => __('Enter the treatment dosage','woocommerce' ),
'desc_tip' => 'true',
'description' => __( 'Enter dosage info for this variation', 'woocommerce' ),
'class' => '',
'value' => get_post_meta( $variation->ID, '_dose_customer_field', true )
)
);
}
// Save custom field on product variation save
add_action( 'woocommerce_save_product_variation', 'save_custom_field_variations', 10, 2 );
function save_custom_field_variations( $variation_id, $i ) {
$_dose_customer_field = $_POST['_dose_customer_field'][$i];
if ( isset( $_dose_customer_field ) ) update_post_meta( $variation_id, '_dose_customer_field', esc_attr( $_dose_customer_field ) );
}
// Add metadata to cart item post.
add_filter( 'woocommerce_add_cart_item_data', 'add_custom_fields_cart_item_data', 10, 2 );
function add_custom_fields_cart_item_data( $cart_item_data, $product_id ){
$cart_item_data['custom_data']['_dose_customer_field'] = 'TEST DATA' /* HOW TO GET DATA FROM CUSTOM FIELD HERE */
$cart_item_data['custom_data']['unique_key'] = md5( microtime().rand() );
WC()->session->set( 'custom_data', $cart_item_data['custom_data'] );
return $cart_item_data;
}
// Display custom meta data on cart and checkout page.
add_filter( 'woocommerce_get_item_data', 'display_custom_fields_cart_item_data', 10, 2 );
function display_custom_fields_cart_item_data($item_data, $cart_item){
if( ! array_key_exists( 'custom_data', $cart_item ) )
return $item_data;
if( array_key_exists( '_dose_customer_field', $cart_item['custom_data'] ) )
$item_data[] = array(
'key' => __('Dose (Customer)', 'woocommerce'),
'value' => $cart_item['custom_data']['_dose_customer_field']
);
return $item_data;
}
// Add metadata to the order.
add_action('woocommerce_checkout_create_order_line_item', 'save_custom_fields_as_order_item_meta', 20, 4);
function save_custom_fields_as_order_item_meta($item, $cart_item_key, $values, $order) {
if( ! isset($values['custom_data']) )
return;
$text_domain ='woocommerce';
if( array_key_exists('_dose_customer_field', $values['custom_data']) ){
$item->update_meta_data( __('Dose (Customer)', $text_domain), $values['custom_data']['_dose_customer_field'] );
}
}
// Frontend & emails: Display data on notifications
add_action( 'woocommerce_order_item_meta_start', 'vp_order_item_display_commodity_code', 10, 4 );
function vp_order_item_display_commodity_code( $item_id, $item, $order, $plain_text ) {
// Not on admin
//if( is_admin() ) return;
if( $value = $item->get_meta('_dose_customer_field') ) {
$value = '<strong>' . __("Dose (Customer)", "woocommerce") . ':</strong> ' . esc_attr( $value );
// On orders
if( is_wc_endpoint_url() )
echo '<div class="vp-ccode"><small>' . $value . '</small></div>';
// On Emails
else
echo '<div>' . $value . '</div>';
}
}
So everything is working except getting the data from the custom fields. It seems odd that I have to create a new array (here called 'custom_data') and add it to the cart_item_data, when the data is already available on the product variation, albeit private.
My question is how do get the metadata within add_custom_fields_cart_item_data()? Is this even the correct approach?
Many thanks
As this custom data exist for the product, you can get it easily and save it as order item custom data (so it will be displayed everywhere):
The complete code (changed the 2 last functions):
// Add custom field inputs to each product variation
add_action( 'woocommerce_variation_options_pricing', 'add_custom_field_to_variations', 10, 3 );
function add_custom_field_to_variations( $loop, $variation_data, $variation ) {
woocommerce_wp_text_input(
array(
'id' => '_dose_customer_field[' . $loop . ']',
'label' => __( 'Dose (Customer)', 'woocommerce' ),
'placeholder' => __('Enter the treatment dosage','woocommerce' ),
'desc_tip' => 'true',
'description' => __( 'Enter dosage info for this variation', 'woocommerce' ),
'class' => '',
'value' => get_post_meta( $variation->ID, '_dose_customer_field', true )
)
);
}
// Save custom field on product variation save
add_action( 'woocommerce_save_product_variation', 'save_custom_field_variations', 10, 2 );
function save_custom_field_variations( $variation_id, $i ) {
$_dose_customer_field = $_POST['_dose_customer_field'][$i];
if ( isset( $_dose_customer_field ) ) update_post_meta( $variation_id, '_dose_customer_field', esc_attr( $_dose_customer_field ) );
}
// Display custom meta data on cart and checkout page.
add_filter( 'woocommerce_get_item_data', 'display_custom_fields_cart_item_data', 10, 2 );
function display_custom_fields_cart_item_data( $item_data, $cart_item ) {
if( $value = $cart_item['data']->get_meta( '_dose_customer_field' ) )
$item_data[] = array(
'key' => __('Dose (Customer)', 'woocommerce'),
'value' => $value
);
return $item_data;
}
// Add metadata to the order item (and display it everywhere).
add_action('woocommerce_checkout_create_order_line_item', 'save_custom_fields_as_order_item_meta', 10, 4);
function save_custom_fields_as_order_item_meta( $item, $cart_item_key, $values, $order ) {
if( $meta_value = $values['data']->get_meta( '_dose_customer_field' ) )
$item->update_meta_data( __('Dose (Customer)', 'woocommerce'), $meta_value );
}
Code goes in functions.php file of your active child theme (or active theme). It should work.

Insert a custom total row on cart and checkout totals in Woocommerce

In woocommerce, I have successfully managed to add a custom field to a Woocommerce simple product and display that value on the additional info tab on a product page.
Now I am totally lost with the final piece of my jigsaw trying to insert a total row in cart and checkout pages with for the total calculated volume.
The custom field is to store the volume in m3 of a furniture item. When a client adds an item to the basket I would like to calculate the total m3 of the shipment by adding the values of all the custom fields together and displaying the total to the customer on the page. Can anyone point me in the right direction of how to add these custom fields and display them please.
So far my code looks like this
// Display Fields using WooCommerce Action Hook
add_action( 'woocommerce_product_options_general_product_data', 'woocom_general_product_data_custom_field' );
function woocom_general_product_data_custom_field() {
// Create a custom text field
// Number Field
woocommerce_wp_text_input(
array(
'id' => '_item_volume',
'label' => __( 'Item Shipping Volume', 'woocommerce' ),
'placeholder' => '',
'description' => __( 'Enter the volume her in m3.', 'woocommerce' ),
'type' => 'number',
'custom_attributes' => array(
'step' => 'any',
'min' => '0.001'
)
)
);
}
// Hook to save the data value from the custom fields
add_action( 'woocommerce_process_product_meta', 'woocom_save_general_proddata_custom_field' );
/** Hook callback function to save custom fields information */
function woocom_save_general_proddata_custom_field( $post_id ) {
// Save Number Field
$number_field = $_POST['_item_volume'];
if( ! empty( $number_field ) ) {
update_post_meta( $post_id, '_item_volume', esc_attr( $number_field ) );
}
}
add_action( 'woocommerce_product_additional_information', 'custom_data_in_product_add_info_tab', 20, 1 );
function custom_data_in_product_add_info_tab( $product ) {
//Product ID - WooCommerce compatibility
$product_id = method_exists( $product, 'get_id' ) ? $product->get_id() : $product->id;
// Get your custom fields data
$custom_field1 = get_post_meta( $product_id, '_item_volume', true );
// Set your custom fields labels (or names)
$label1 = __( 'Shipping Volume m3', 'woocommerce');
// The Output
echo '<h3>'. __('Item Shipping Volume', 'woocommerce') .'</h3>
<table class="custom-fields-data">
<tbody>
<tr class="custom-field1">
<th>'. $label1 .'</th>
<td>'. $custom_field1 .'</td>
</tr>
</tbody>
</table>';
}
The following will display the total cart volume in cart and checkout page:
add_action( 'woocommerce_cart_totals_before_shipping', 'display_cart_volume_total', 20 );
add_action( 'woocommerce_review_order_before_shipping', 'display_cart_volume_total', 20 );
function display_cart_volume_total() {
$total_volume = 0;
// Loop through cart items and calculate total volume
foreach( WC()->cart->get_cart() as $cart_item ){
$product_volume = (float) get_post_meta( $cart_item['product_id'], '_item_volume', true );
$total_volume += $product_volume * $cart_item['quantity'];
}
if( $total_volume > 0 ){
// The Output
echo ' <tr class="cart-total-volume">
<th>' . __( "Total Shipping Volume", "woocommerce" ) . '</th>
<td data-title="total-volume">' . number_format($total_volume, 2) . ' m3</td>
</tr>';
}
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.

Categories