Show Custom Field Product Information on WooCommerce Checkout Page - php

I'm trying to display multiple custom product fields on the checkout page. I've found the below code which works for one custom field but how can I add multiple custom fields to it?
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;
}

you can define $meta_keys as array
$meta_keys = array('custom_time','custom_time2'); // or more than tow
and other Field
$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;

Related

Display purchase note and attribute on cart and checkout page in WooCommerce

The following code works and adds the purchase note to the cart items.
add_filter( 'woocommerce_get_item_data', 'wc_test', 10, 2 );
function wc_test ( $other_data, $cart_item ){
$post_data = get_post( $cart_item['product_id'] );
$other_data[] = array( 'name' => $post_data->_purchase_note );
return $other_data;
}
However, I always get ":" as result, for products that don't have a note.
I also need to add a specific attribute aswell under the note.
Any advice?
The colon is automatically added to the key. Because you only use name, this will be added at the end.
You can use get_purchase_note()
So you get:
// Display on cart & checkout pages
function filter_woocommerce_get_item_data( $item_data, $cart_item ) {
// Get an instance of the WC_Product object
$product = $cart_item['data'];
// Get purchase_note
$purchase_note = $product->get_purchase_note();
// Get the product attribute value (adjust if desired)
$attribute = $product->get_attribute( 'pa_color' );
// When empty
if ( empty ( $attribute ) ) {
$attribute = '';
}
// NOT empty
if ( ! empty( $purchase_note ) ) {
$item_data[] = array(
'key' => __( 'Note', 'woocommerce' ),
'value' => $purchase_note . $attribute,
'display' => $purchase_note . $attribute,
);
}
return $item_data;
}
add_filter( 'woocommerce_get_item_data', 'filter_woocommerce_get_item_data', 10, 2 );

WooCommerce - Overriding ajax add to cart not working

I'm trying to override the ajax add to cart function of WooCoommerce and add this simple condition.
$base = true;
if($base){
return the default error just to test...
}else{
default functionality ...
}
I get the idea from here and simply add my condition to it just to test but it doesn't work.
function woocommerce_ajax_add_to_cart() {
global $woocommerce;
check_ajax_referer( 'add-to-cart', 'security' );
$product_id = apply_filters('woocommerce_add_to_cart_product_id', absint( $_POST['product_id'] ) );
$quantity = empty( $_POST['quantity'] ) ? 1 : apply_filters( 'woocommerce_stock_amount', $_POST['quantity'] );
$passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $product_id, $quantity );
$base = true;
if($base){//simple condition
header( 'Content-Type: application/json; charset=utf-8' );
// If there was an error adding to the cart, redirect to the product page to show any errors
$data = array(
'error' => true,
'product_url' => apply_filters('woocommerce_cart_redirect_after_error', get_permalink( $product_id ), $product_id)
);
$woocommerce->set_messages();
echo json_encode( $data );
}else{
if ( $passed_validation && $woocommerce->cart->add_to_cart( $product_id, $quantity ) ) {
do_action( 'woocommerce_ajax_added_to_cart', $product_id );
if ( get_option( 'woocommerce_cart_redirect_after_add' ) == 'yes' ) {
woocommerce_add_to_cart_message( $product_id );
$woocommerce->set_messages();
}
// Return fragments
woocommerce_get_refreshed_fragments();
} else {
header( 'Content-Type: application/json; charset=utf-8' );
// If there was an error adding to the cart, redirect to the product page to show any errors
$data = array(
'error' => true,
'product_url' => apply_filters('woocommerce_cart_redirect_after_error', get_permalink( $product_id ), $product_id)
);
$woocommerce->set_messages();
echo json_encode( $data );
}
}
die();
}
add_action('wp_ajax_woocommerce_add_to_cart', 'woocommerce_ajax_add_to_cart');
add_action('wp_ajax_nopriv_woocommerce_add_to_cart', 'woocommerce_ajax_add_to_cart');
Am I missing something?
Yes, you missed the whole thing. Instead of wp_ajax_woocommerce_add_to_cart the action you need is woocommerce_add_to_cart and you don't need the wp_ajax_nopriv_woocommerce_add_to_cart action at all.
Instead of that source, you should be taking the idea from here. It is located on woocommerce/includes/class-wc-ajax.php.
Take note of self::get_refreshed_fragments(), used WC_AJAX::get_refreshed_fragments() instead.
Overall, your code should be:
function woocommerce_ajax_add_to_cart() {
ob_start();
// phpcs:disable WordPress.Security.NonceVerification.Missing
if ( !isset( $_POST[ 'product_id' ] ) ) {
return;
}
$product_id = apply_filters( 'woocommerce_add_to_cart_product_id', absint( $_POST[ 'product_id' ] ) );
$product = wc_get_product( $product_id );
$quantity = empty( $_POST[ 'quantity' ] ) ? 1 : wc_stock_amount( wp_unslash( $_POST[ 'quantity' ] ) );
$passed_validation = apply_filters( 'woocommerce_add_to_cart_validation', true, $product_id, $quantity );
$product_status = get_post_status( $product_id );
$variation_id = 0;
$variation = array();
if ( $product && 'variation' === $product->get_type() ) {
$variation_id = $product_id;
$product_id = $product->get_parent_id();
$variation = $product->get_variation_attributes();
}
$base = true;
if ( $base ) { /** Your condition here **/
// If there was an error adding to the cart, redirect to the product page to show any errors.
$data = array(
'error' => true,
'product_url' => apply_filters( 'woocommerce_cart_redirect_after_error', get_permalink( $product_id ), $product_id ),
);
wp_send_json( $data );
} else {
if ( $passed_validation && false !== WC()->cart->add_to_cart( $product_id, $quantity, $variation_id, $variation ) && 'publish' === $product_status ) {
do_action( 'woocommerce_ajax_added_to_cart', $product_id );
if ( 'yes' === get_option( 'woocommerce_cart_redirect_after_add' ) ) {
wc_add_to_cart_message( array( $product_id => $quantity ), true );
}
WC_AJAX::get_refreshed_fragments();
} else {
// If there was an error adding to the cart, redirect to the product page to show any errors.
$data = array(
'error' => true,
'product_url' => apply_filters( 'woocommerce_cart_redirect_after_error', get_permalink( $product_id ), $product_id ),
);
wp_send_json( $data );
}
}
// phpcs:enable
}
add_action( 'woocommerce_add_to_cart', 'woocommerce_ajax_add_to_cart' );
EDIT: You may be in a known issue (also here) where the action woocommerce_add_to_cart is being called multiple times because of the function WC()->cart->add_to_cart(...).
Base on this source, you can solve it by adding conditional statement so that the WC()->cart->add_to_cart(...) won't cause the issue.
I don't know what you are trying to achieve, but base on your code it looks like you just want to add another condition before adding the products into the cart.
In that case, you could do the following.
function woocommerce_ajax_add_to_cart() {
ob_start();
if ( !isset( $_POST[ 'product_id' ] ) ) {
return;
}
$found = false;
$base = true;
if ( $base ) { /** Your condition here **/
// If there was an error adding to the cart, redirect to the product page to show any errors.
$data = array(
'error' => true,
'product_url' => apply_filters( 'woocommerce_cart_redirect_after_error', get_permalink( $product_id ), $product_id ),
);
wp_send_json( $data );
}else{
if ( sizeof( WC()->cart->get_cart() ) > 0 ) { //check if product already in cart
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->id == $product_id )
$found = true;
}
if ( ! $found ){ // if product not found, add it
WC()->cart->add_to_cart( $product_id, $quantity, $variation_id, $variation );
}
} else {
WC()->cart->add_to_cart( $product_id, $quantity, $variation_id, $variation ); // if no products in cart, add it
}
}
}
add_action( 'woocommerce_add_to_cart', 'woocommerce_ajax_add_to_cart' );
OR
function woocommerce_ajax_add_to_cart() {
ob_start();
if ( !isset( $_POST[ 'product_id' ] ) ) {
return;
}
$found = false;
$base = true;
if ( sizeof( WC()->cart->get_cart() ) > 0 ) { //check if product already in cart
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->id == $product_id )
$found = true;
}
if ( ! $found ){ // if product not found, add it
if ( $base ) { /** Your condition here **/
$data = array(
'error' => true,
'product_url' => apply_filters( 'woocommerce_cart_redirect_after_error', get_permalink( $product_id ), $product_id ),
);
wp_send_json( $data );
}else{
WC()->cart->add_to_cart( $product_id, $quantity, $variation_id, $variation );
}
}
} else {
WC()->cart->add_to_cart( $product_id, $quantity, $variation_id, $variation ); // if no products in cart, add it
}
}
add_action( 'woocommerce_add_to_cart', 'woocommerce_ajax_add_to_cart' );

Single product custom date fields not validated and saved in Woocommerce

I've added two customer date inputs to the single product page. I need them to be required and validated before adding to the cart, and would also like the dates to be shown on the cart/checkout page and in the order emails.
I found the snippets needed here, however it was only for one custom field so I adjusted to make it for two: https://www.kathyisawesome.com/add-a-custom-field-to-woocommerce-product/
The input fields show up fine, but once you hit the Add to Cart button it doesn't carry throughout the order.
Here is the code used in my functions.php file:
/*
* Display inputs on single product page
*/
function amp_custom_option_1(){
$value = isset( $_POST['_est_delivery'] ) ? sanitize_text_field( $_POST['_est_delivery'] ) : '';
printf( '<div id="dates"><div class="delivery"><label>%s</label><input name="_est_delivery" value="%s" type="date" required /></div>', __( 'Estimated Delivery Date:', 'amp-plugin-textdomain-1' ), esc_attr( $value ) );
}
add_action( 'woocommerce_before_add_to_cart_form', 'amp_custom_option_1', 9 );
function amp_custom_option_2(){
$value = isset( $_POST['_est_pickup'] ) ? sanitize_text_field( $_POST['_est_pickup'] ) : '';
printf( '<div class="pickup"><label>%s</label><input name="_est_pickup" value="%s" type="date" required /></div></div>', __( 'Estimated Pickup Date:', 'amp-plugin-textdomain-2' ), esc_attr( $value ) );
}
add_action( 'woocommerce_before_add_to_cart_form', 'amp_custom_option_2', 9 );
/*
* Validate when adding to cart
*/
function amp_add_to_cart_validation_1($passed, $product_id, $qty){
if( isset( $_POST['_est_delivery'] ) && sanitize_text_field( $_POST['_est_delivery'] ) == '' ){
$product = wc_get_product( $product_id );
wc_add_notice( sprintf( __( '%s cannot be added to the cart until you enter a delivery date.', 'amp-plugin-textdomain-1' ), $product->get_title() ), 'error' );
return false;
}
return $passed;
}
add_filter( 'woocommerce_add_to_cart_validation', 'amp_add_to_cart_validation_1', 10, 3 );
function amp_add_to_cart_validation_2($passed, $product_id, $qty){
if( isset( $_POST['_est_pickup'] ) && sanitize_text_field( $_POST['_est_pickup'] ) == '' ){
$product = wc_get_product( $product_id );
wc_add_notice( sprintf( __( '%s cannot be added to the cart until you enter a pickup date.', 'amp-plugin-textdomain-2' ), $product->get_title() ), 'error' );
return false;
}
return $passed;
}
add_filter( 'woocommerce_add_to_cart_validation', 'amp_add_to_cart_validation_2', 10, 3 );
/*
* Add custom data to the cart item
*/
function amp_add_cart_item_data_1( $cart_item, $product_id ){
if( isset( $_POST['_est_delivery'] ) ) {
$cart_item['est_delivery'] = sanitize_text_field( $_POST['_est_delivery'] );
}
return $cart_item;
}
add_filter( 'woocommerce_add_cart_item_data', 'amp_add_cart_item_data_1', 10, 2 );
function amp_add_cart_item_data_2( $cart_item, $product_id ){
if( isset( $_POST['_est_pickup'] ) ) {
$cart_item['est_pickup'] = sanitize_text_field( $_POST['_est_pickup'] );
}
return $cart_item;
}
add_filter( 'woocommerce_add_cart_item_data', 'amp_add_cart_item_data_2', 10, 2 );
/*
* Load cart data from session
*/
function amp_get_cart_item_from_session_1( $cart_item, $values ) {
if ( isset( $values['est_delivery'] ) ){
$cart_item['est_delivery'] = $values['est_delivery'];
}
return $cart_item;
}
add_filter( 'woocommerce_get_cart_item_from_session', 'amp_get_cart_item_from_session_1', 20, 2 );
function amp_get_cart_item_from_session_2( $cart_item, $values ) {
if ( isset( $values['est_pickup'] ) ){
$cart_item['est_pickup'] = $values['est_pickup'];
}
return $cart_item;
}
add_filter( 'woocommerce_get_cart_item_from_session', 'amp_get_cart_item_from_session_2', 20, 2 );
/*
* Add meta to order item
*/
function amp_add_order_item_meta_1( $item_id, $values ) {
if ( ! empty( $values['est_delivery'] ) ) {
woocommerce_add_order_item_meta( $item_id, 'est_delivery', $values['est_delivery'] );
}
}
add_action( 'woocommerce_add_order_item_meta', 'amp_add_order_item_meta_1', 10, 2 );
function amp_add_order_item_meta_2( $item_id, $values ) {
if ( ! empty( $values['est_pickup'] ) ) {
woocommerce_add_order_item_meta( $item_id, 'est_pickup', $values['est_pickup'] );
}
}
add_action( 'woocommerce_add_order_item_meta', 'amp_add_order_item_meta_2', 10, 2 );
/*
* Get item data to display in cart
*/
function amp_get_item_data_1( $other_data, $cart_item ) {
if ( isset( $cart_item['est_delivery'] ) ){
$other_data[] = array(
'name' => __( 'Estimated Delivery Date:', 'amp-plugin-textdomain-1' ),
'value' => sanitize_text_field( $cart_item['est_delivery'] )
);
}
return $other_data;
}
add_filter( 'woocommerce_get_item_data', 'amp_get_item_data_1', 10, 2 );
function amp_get_item_data_2( $other_data, $cart_item ) {
if ( isset( $cart_item['est_pickup'] ) ){
$other_data[] = array(
'name' => __( 'Estimated Pickup Date', 'amp-plugin-textdomain-2' ),
'value' => sanitize_text_field( $cart_item['est_pickup'] )
);
}
return $other_data;
}
add_filter( 'woocommerce_get_item_data', 'amp_get_item_data_2', 10, 2 );
/*
* Show custom field in order overview
*/
function amp_order_item_product_1( $cart_item, $order_item ){
if( isset( $order_item['est_delivery'] ) ){
$cart_item_meta['est_delivery'] = $order_item['est_delivery'];
}
return $cart_item;
}
add_filter( 'woocommerce_order_item_product', 'amp_order_item_product_1', 10, 2 );
function amp_order_item_product_2( $cart_item, $order_item ){
if( isset( $order_item['est_pickup'] ) ){
$cart_item_meta['est_pickup'] = $order_item['est_pickup'];
}
return $cart_item;
}
add_filter( 'woocommerce_order_item_product', 'amp_order_item_product_2', 10, 2 );
/*
* Add the field to order emails
*/
function amp_email_order_meta_fields_1( $fields ) {
$fields['est_delivery'] = __( 'Estimated Delivery Date:', 'amp-plugin-textdomain-1' );
return $fields;
}
add_filter('woocommerce_email_order_meta_fields', 'amp_email_order_meta_fields_1');
function amp_email_order_meta_fields_2( $fields ) {
$fields['est_delivery'] = __( 'Estimate Pickup Date:', 'amp-plugin-textdomain-2' );
return $fields;
}
add_filter('woocommerce_email_order_meta_fields', 'amp_email_order_meta_fields_2');
I'm not sure what is wrong with my code? Any help is appreciated.
There was some errors and mistakes. I have changed and removed some hooks, remove unnecessary code, merged functions, revisited all your code. As Your 2 dates fields are on single product pages, they will be related to cart items and order items (so order items meta data).
I have set your 2 date fields slugs and labels in the first function, inside an array. Then I call that function everywhere else and I use a foreach loop to process each field. This avoid repetitions, optimize and compact the code.
The code (commented):
// Utility function that contain the 2 field keys and labels pairs used on all other functions
function get_date_label_keys(){
$text_domain = 'woocommerce';
return array( 'est_delivery' => __( 'Estimated Delivery Date', $text_domain ),
'est_pickup' => __( 'Estimated Pickup Date', $text_domain ) );
}
// Display custom fields on single product page (hook replaced)
add_action( 'woocommerce_before_add_to_cart_button', 'amp_display_custom_fields', 20 );
function amp_display_custom_fields(){
echo '<div id="dates">';
// Loop through each custom field
foreach( get_date_label_keys() as $key => $label ){
$class = str_replace('est_', '', $key); // The class
$value = isset($_POST[$key]) ? sanitize_text_field($_POST[$key]) : ''; // Display the value
printf( '<div class="%s"><label>%s:</label> <input type="date" name="%s" value="%s" required /></div>', $class, $label, $key, $value );
}
echo '</div><br clear="all">';
}
// Add to cart fields validation (in case of need)
add_filter( 'woocommerce_add_to_cart_validation', 'amp_add_to_cart_validation', 20, 3 );
function amp_add_to_cart_validation( $passed, $product_id, $qty ){
// Loop through each custom field
foreach( get_date_label_keys() as $key => $label ){
if( isset( $_POST[$key] ) && empty( $_POST[$key] ) ){
wc_add_notice( sprintf( __( '%s cannot be added to the cart until you enter a delivery date.', $domain ), get_the_title() ), 'error' );
$passed = false;
}
}
return $passed;
}
// Add to cart items the custom data
add_filter( 'woocommerce_add_cart_item_data', 'amp_add_cart_item_data', 20, 2 );
function amp_add_cart_item_data( $cart_item, $product_id ){
// Loop through each custom field
foreach( get_date_label_keys() as $key => $label ){
if( isset( $_POST[$key] ) )
$cart_item['dates'][$key] = sanitize_text_field( $_POST[$key] );
}
return $cart_item;
}
// Display the dates in cart items on cart and checkout pages
add_filter( 'woocommerce_get_item_data', 'amp_get_item_data', 20, 2 );
function amp_get_item_data( $item_data, $cart_item = null ) {
// Loop through each custom field
foreach( get_date_label_keys() as $key => $label ){
if ( isset( $cart_item['dates'][$key] ) )
$item_data[] = array(
'name' => $label,
'value' => sanitize_text_field( $cart_item['dates'][$key] )
);
}
return $item_data;
}
// Add order item meta data and Display the data in order items (hook replaced)
add_action( 'woocommerce_checkout_create_order_line_item', 'amp_add_order_item_meta', 20, 4 );
function amp_add_order_item_meta( $item, $cart_item_key, $values, $order ) {
foreach( get_date_label_keys() as $key => $label ){
// Loop through each custom field
if ( ! empty( $values['dates'][$key] ) )
$item->update_meta_data( $label, $values['dates'][$key] );
}
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
On cart page (and checkout too):
Order received and order view pages (in admin order edit pages and email notifications too):

Displaying custom field of product variations within Woocommerce orders and emails

I successfully added a custom field for product variations within the backend of WooCommerce and was able to display its value. I'd like to contain this value within order and emails as well.
//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;
}
I'm using the following to display the custom field's value within the cart.
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;
}
Further as for now I'm displaying its value below the product price / total of each item within cart/checkout template with the following
echo get_post_meta( $_product->get_id(), '_text_field', true );
How about displaying the value of this field within orders and emails?
Updated: To display that in order pages and email notifications try the following additional functions (I have made some changes in the woocommerce_get_item_data hooked function, so you need to replace it with the following one):
// Save custom field value in cart item
add_filter( 'woocommerce_add_cart_item_data', 'save_custom_field_in_cart_object', 30, 3 );
function save_custom_field_in_cart_object( $cart_item_data, $product_id, $variation_id ) {
// Get the correct Id to be used
$the_id = $variation_id > 0 ? $variation_id : $product_id;
if( $value = get_post_meta( $the_id, '_text_field', true ) )
$cart_item_data['custom_data'] = sanitize_text_field( $value );
return $cart_item_data;
}
// Display on cart and checkout pages
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( isset( $cart_item['custom_data'] ) ){
$cart_data[] = array(
'name' => __( 'Additional Monthly Fee', 'woocommerce' ),
'value' => $cart_item['custom_data']
);
}
return $cart_data;
}
// Save custom field value in order items meta data
add_action( 'woocommerce_add_order_item_meta', 'add_custom_field_to_order_item_meta', 20, 3 );
function add_custom_field_to_order_item_meta( $item_id, $values, $cart_item_key ) {
if( isset( $values['custom_data'] ) )
wc_add_order_item_meta( $item_id, __( 'Additional Monthly Fee', 'woocommerce' ), $values['custom_data'] );
}
Code goes in function.php file of your active child theme (or theme). Tested and works.
It will display the custom field label and value in all Order pages and in email notifications too.

Saving custom field data from Admin WooCommerce product data metabox

In Woocommerce I use some custom fields for product specifications, and save the specifications in the post_meta.
I'm trying to make an if loop to write down in the post_meta another product specification.
The code I now use is:
add_action( 'woocommerce_product_options_general_product_data', 'BTW_field' );
function BTW_field() {
woocommerce_wp_radio(
array(
'id' => '_BTW',
'default' => '21% BTW',
'required' => true,
'options' => array(
'Prijs is incl. 21% BTW' => '21% BTW',
'Margeproduct' => 'Marge Product',
)
)
);
}
add_action( 'woocommerce_process_product_meta', 'BTW_save' );
function BTW_save( $post_id ){
$BTW = $_POST['_BTW'];
if( !empty( $BTW ) )
update_post_meta( $post_id, '_BTW', esc_attr( $BTW ) );
}
An now I try to rewrite the BTW_save function so it will save another post_meta.
function BTW_save( $post_id ){
$BTW = $_POST['_BTW'];
if( !empty( $BTW ) ){
update_post_meta( $post_id, '_BTW', esc_attr( $BTW ) );
}
if ($BTW == "Margeproduct (vrijgesteld van BTW)"){
$BTW2 = "Margeproduct*"
} else {
$BTW2 = "21%"
}
update_post_meta( $post_id, '_BTW_NAME', esc_attr( $BTW2 ) );
}
I don't know how I can check if $BTW is equal to the post_meta _BTW and how I can rewrite it so $BTW2 will also save in the post meta as _BTW_NAME.
Updated: As you are setting 2 different values, it could be better to use a select field instead.
Also I have make some changes in your code regarding correct variable naming and field keys naming (You should be able to rename them easily keeping in mind that lowercase and underscores are recommended).
Here is the code:
add_action( 'woocommerce_product_options_general_product_data', 'add_btw_field' );
function add_btw_field() {
global $post;
// Get the selected value
$value = get_post_meta( $post->ID, '_btw', true );
if( empty( $value ) ) $value = 'btw'; // Default value
woocommerce_wp_select( array(
'id' => 'btw_select',
'label' => __( 'BTW-prijsopties', 'woocommerce' ),
'options' => array(
'btw' => __( '21% BTW', 'woocommerce' ),
'marge' => __( 'Marge Product', 'woocommerce' ),
),
'value' => $value, // Displaying the selected value
) );
}
add_action( 'woocommerce_process_product_meta', 'save_btw_field' );
function save_btw_field( $post_id ){
if( empty( $_POST['btw_select'] ) ) return; // exit (in case of)
update_post_meta( $post_id, '_btw', esc_attr( $_POST['btw_select'] ) );
if ( $_POST['btw_select'] == 'btw' )
$label = __( 'BTW 21%', 'woocommerce' );
else
$label = __( 'Margeproduct (vrijgesteld van BTW)', 'woocommerce' );
update_post_meta( $post_id, '_btw_label', esc_attr( $label ) );
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
Tested and works. You will get something like that:
By default when creating or updating a product, both custom fields will be saved for 'btw' option as product meta data…
You will be able to get both product post_meta custom fields values using get_post_meta():
// Set HERE the product ID (or get it dynamically)
$product_id = 37;
$btw = get_post_meta( $product_id, '_btw', true ); // Values can be 'yes' or 'no'
$btw_label = get_post_meta( $product_id, '_btw_label', true );
// Output (testing):
echo $btw_label;

Categories