Product custom checkbox option that changes Woocommerce cart item price - php

The following code displays a custom checkbox before add to cart button on single product pages:
add_action( 'woocommerce_before_add_to_cart_button', 'output_custom_text_field', 0 );
function output_custom_text_field() {
//Lots of code then:
<input type="checkbox" id="option1" name="option1">
}
Now I would like to trap/capture this checkbox option in Woocommerce session and then make a custom price calculations in the following code:
function final_cart_update( $cart_object ) {
foreach ( $cart_object->get_cart() as $cart_item ) {
// get the custom pricing for this product
if (isset( $_POST['option1'])) {
$pricing_custom = get_post_meta( $cart_item['product_id'], '_number_field_1', true );
}
// get product price
$price = floatval( $cart_item['data']->get_price() );
// set new price
$cart_item['data']->set_price( $price + $pricing_custom );
}
}
add_action( 'woocommerce_before_calculate_totals', 'final_cart_update', 99, 1 );
What is missing is the part that will capture the checkbox option to set it in sessions, like:
if (isset( $_POST['option1'])) {
// Set it in session
}
Any help is appreciated.
Admin Part of the code →
/*-------------------------------------------*/
/* 5. Adding Custom Field */
/*-------------------------------------------*/
// Add custom fields in "product data" settings metabox ("Advanced" tab)
add_action('woocommerce_product_options_advanced','woocious_add_custom_field_product_dashboard');
function woocious_add_custom_field_product_dashboard(){
global $post;
echo '<div class="product_custom_field">';
// Checkbox Field
woocommerce_wp_checkbox( array(
'id' => 'woocious_custom_services_fields',
'description' => __('Select if you want add on services', 'woocious'),
'label' => __('Display custom add on services', 'woocious'),
'desc_tip' => 'true',
) );
// Minimum Letter Text Box
woocommerce_wp_text_input( array(
'id' => 'addon_service_1',
'label' => __('Service 1', 'woocommerce'),
'description' => __('set custom minimum Lettering text field', 'woocommerce'),
'desc_tip' => 'true',
) );
// Number Field
woocommerce_wp_text_input(
array(
'id' => '_number_field_1',
'label' => __( 'Service amount 1', 'woocommerce' ),
'placeholder' => '',
'desc_tip' => false,
'description' => __( "Please enter the service amount", 'woocommerce' ),
'type' => 'number',
'desc_tip' => 'true',
'custom_attributes' => array(
'step' => 'any',
'min' => '0'
)
)
);
// Maximum Letter Text Box
woocommerce_wp_text_input( array(
'id' => 'addon_service_2',
'label' => __('Service 2', 'woocommerce'),
'description' => __('set custom maximum Lettering text field', 'woocommerce'),
'desc_tip' => 'true'
) );
// Number Field
woocommerce_wp_text_input(
array(
'id' => '_number_field_2',
'label' => __( 'Service amount 2', 'woocommerce' ),
'placeholder' => '',
'desc_tip' => false,
'description' => __( "Please enter the service amount", 'woocommerce' ),
'type' => 'number',
'desc_tip' => 'true',
'custom_attributes' => array(
'step' => 'any',
'min' => '0'
)
)
);
echo '</div>';
}
// Save Inputted Entries, in the Product Dashboard Text Fields.
add_action('woocommerce_process_product_meta', 'woocommerce_product_custom_fields_save');
function woocommerce_product_custom_fields_save($post_id){
// Checkbox Field
$checkbox = isset( $_POST['woocious_custom_services_fields'] ) ? 'yes' : 'no';
update_post_meta( $post_id, 'woocious_custom_services_fields', $checkbox );
// Save Minimum Letters
if ( isset( $_POST['addon_service_1'] ) )
update_post_meta($post_id, 'addon_service_1', sanitize_text_field( $_POST['addon_service_1'] ) );
// Save Maximum Letters
if ( isset( $_POST['addon_service_2'] ) )
update_post_meta($post_id, 'addon_service_2', sanitize_text_field( $_POST['addon_service_2'] ) );
// Save the services amount
if ( isset( $_POST['_number_field_1'] ) )
update_post_meta($post_id, '_number_field_1', sanitize_text_field( $_POST['_number_field_1'] ) );
}
Outputting HTML on Product Page →
// Output Custom Text Field to Product Page
add_action( 'woocommerce_before_add_to_cart_button', 'output_custom_text_field', 0 );
function output_custom_text_field() {
// Get the checkbox value
$custom_option = get_post_meta( $post->ID, 'woocious_custom_services_fields', true );
// If is single product page and have the "custom text option" enabled we display the field
if ( is_product() && ! empty($custom_option) ) {
?>
<div class="woociousbuy_inner">
<div class="woociousbuy_two">
<h3>Add on Services</h3>
<input type="checkbox" id="option1" name="option1">
<label for="option1"><?php global $post; echo get_post_meta($post->ID,'addon_service_1',true);?>
<svg class="svgcheckbox" width="100" height="100" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"><path d="M13 50.986L37.334 75 88 25" stroke-width="15" stroke="#66bb6a" fill="none" fill-rule="evenodd" stroke-dasharray="150" stroke-dashoffset="150"/></svg>
</label><span class="woocense_price bold">€<?php global $post; echo get_post_meta($post->ID,'_number_field_1',true);?></span>
</div>
<div class="woociousbuy_inner">
<input type="checkbox" id="option2" name="option2"/>
<label for="option2"><?php global $post; echo get_post_meta($post->ID,'addon_service_2',true);?>
<svg class="svgcheckbox" width="100" height="100" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"><path d="M13 50.986L37.334 75 88 25" stroke-width="15" stroke="#66bb6a" fill="none" fill-rule="evenodd" stroke-dasharray="150" stroke-dashoffset="150"/></svg>
</label><span class="woocense_price bold">€<?php global $post; echo get_post_meta($post->ID,'_number_field_2',true);?></span>
</div>
</div>
<?php
}
}

You don't need to use any session for that. Use woocommerce_add_cart_item_data filter hook like:
add_action( 'woocommerce_before_add_to_cart_button', 'custom_product_option_checkbox_field' );
function custom_product_option_checkbox_field() {
echo '<p><label><input type="checkbox" id="option1" name="option1"> '.__("Option 1").'</label></p>';
}
// Add selected add-on option as custom cart item data
add_filter( 'woocommerce_add_cart_item_data', 'filter_add_cart_item_data_callback', 10, 3 );
function filter_add_cart_item_data_callback( $cart_item_data, $product_id, $variation_id ) {
if ( isset( $_POST['option1'] ) && $pricing_custom = get_post_meta( $product_id, '_number_field_1', true ) ) {
$cart_item_data['pricing_custom'] = $pricing_custom;
$cart_item_data['unique_key'] = md5( microtime().rand() ); // Make each item unique
}
return $cart_item_data;
}
// Change the product price
add_action( 'woocommerce_before_calculate_totals', 'action_before_calculate_totals_callback', 10, 1 );
function action_before_calculate_totals_callback( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Avoiding hook repetition and price calculation problems
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// Loop through cart items
foreach ( $cart->get_cart() as $cart_item ) {
if ( isset( $cart_item['pricing_custom'] ) ) {
// Set the calculated price
$cart_item['data']->set_price( $cart_item['data']->get_price() + $cart_item['pricing_custom'] );
}
}
}
Code goes in functions.php file of your active child theme (or active theme). Tested and works.

Related

Woocommerce add order meta from checkbox [duplicate]

Am using the snippet below to show a custom checkbox for all products but would like to hide/not show it if product with ID 32 is in cart. How do i modify this code to achieve that? Thanks in advance.
add_action( 'woocommerce_review_order_before_submit', 'bbloomer_add_checkout_privacy_policy', 9 );
function bbloomer_add_checkout_privacy_policy() {
woocommerce_form_field( 'privacy_policy', array(
'type' => 'checkbox',
'class' => array('form-row privacy'),
'label_class' => array('woocommerce-form__label woocommerce-form__label-for-checkbox checkbox'),
'input_class' => array('woocommerce-form__input woocommerce-form__input-checkbox input-checkbox'),
'required' => true,
'label' => 'I\'ve read and accept the Privacy Policy',
));
}
// Show notice if customer does not tick
add_action( 'woocommerce_checkout_process', 'bbloomer_not_approved_privacy' );
function bbloomer_not_approved_privacy() {
if ( ! (int) isset( $_POST['privacy_policy'] ) ) {
wc_add_notice( __( 'Please acknowledge the Privacy Policy' ), 'error' );
}
}
Before you actually show the checkbox field, you will first have to go through the cart to see if the productID is NOT present.
Same for the validation, as it is a required field and would otherwise still be a required field, even though it is not present.
So you get:
// Function to check if a certain product ID is in cart
function is_product_in_cart() {
// Check if product in cart
// Multiple product IDs can be entered, separated by a comma
$targeted_ids = array( 32, 1234, 5678 );
// Flag no product in cart
$flag = false;
// WC Cart NOT null
if ( ! is_null( WC()->cart ) ) {
// Loop through cart items
foreach( WC()->cart->get_cart() as $cart_item ) {
// Check cart item for defined product Ids
if ( in_array( $cart_item['product_id'], $targeted_ids ) ) {
// Product is in cart
$flag = true;
// Break loop
break;
}
}
}
return $flag;
}
// Add field
function action_woocommerce_review_order_before_submit() {
// NOT true
if ( ! is_product_in_cart() ) {
// Add checkbox
woocommerce_form_field( 'privacy_policy', array(
'type' => 'checkbox',
'class' => array( 'form-row privacy' ),
'label_class' => array( 'woocommerce-form__label woocommerce-form__label-for-checkbox checkbox' ),
'input_class' => array( 'woocommerce-form__input woocommerce-form__input-checkbox input-checkbox' ),
'required' => true,
'label' => 'I\'ve read and accept the Privacy Policy',
));
}
}
add_action( 'woocommerce_review_order_before_submit', 'action_woocommerce_review_order_before_submit', 9 );
// Validate
function action_woocommerce_checkout_process() {
// NOT true
if ( ! is_product_in_cart() ) {
// NOT isset
if ( ! isset( $_POST['privacy_policy'] ) ) {
wc_add_notice( __( 'Please acknowledge the Privacy Policy', 'woocommerce' ), 'error' );
}
}
}
add_action( 'woocommerce_checkout_process', 'action_woocommerce_checkout_process', 10, 0 );
// Save field
function action_woocommerce_checkout_create_order( $order, $data ) {
// Isset
if ( isset( $_POST['privacy_policy'] ) ) {
$order->update_meta_data( 'privacy_policy', sanitize_text_field( $_POST['privacy_policy'] ) );
}
}
add_action( 'woocommerce_checkout_create_order', 'action_woocommerce_checkout_create_order', 10, 2 );

How to calculate and update sales price in woocommerce product page

I inserted two radio buttons as product add ons by using the following to calculate extra packaging cost. But I have two problems.
First instead of getting the value of my custom field eg 4.35 it gets a value of 4.00.
Second how can I update the sales price in my product page when I choose an option
function add_custom_fees_before_add_to_cart() {
global $product;
$myfee = floatval(get_post_meta(get_the_ID(), '_skrprom', TRUE)) + floatval(0.90);
$args = array(
'type' => 'radio',
'class' => array( 'form-row-wide' ),
'options' => array(
'' => 'Τηλεφωνική Παραγγελία',
$myfee => 'Έξοδα Συσκευασίας '.$myfee.'€',
),
'default' => ''
);
?>
<div class="custom-fees-wrap">
<label for="iconic-engraving"><?php _e( 'Customize Your Order!', 'textdomain' ); ?></label>
<?php woocommerce_form_field( 'custom_fees', $args, '' ); ?>
</div>
<?php
}
add_action( 'woocommerce_before_add_to_cart_button', 'add_custom_fees_before_add_to_cart', 99 );
function save_value_add_cart_item_data( $cart_item_data, $product_id, $variation_id ) {
$custom_fees = filter_input( INPUT_POST, 'custom_fees' );
if ( empty( $custom_fees ) ) {
return $cart_item_data;
}
$cart_item_data['custom_fees'] = $custom_fees;
return $cart_item_data;
}
add_filter( 'woocommerce_add_cart_item_data', 'save_value_add_cart_item_data', 99, 3 );
function calculate_add_cart_fee() {
global $woocommerce;
$cart_items = $woocommerce->cart->get_cart();
foreach( $cart_items as $key => $item ) {
if( !isset( $item['custom_fees'] ) && empty( $item['custom_fees'] ) ) continue;
$woocommerce->cart->add_fee( __('Έξοδα Συσκευασίας', 'textdomain'), $item['custom_fees'] );
}
}
add_action( 'woocommerce_cart_calculate_fees', 'calculate_add_cart_fee', 99 );

Display custom select form in "Quick View" window in WooCommerce

I use the code, that on the product editing page shows the checkbox "Roast Level". When the manager clicks on this checkbox, a select box appears on the page of a single product, allowing the customer to select "Roast Level".
When selecting and adding a product to the cart, the selected value appears in the cart itself. This value is also shown on the checkout page, on the "Thank You" page, in the order, on the email notification, and on the order editing page in the admin panel.
Here is the code:
// Display Checkbox Field
add_action('woocommerce_product_options_general_product_data', 'roast_custom_field_add');
function roast_custom_field_add() {
global $post;
// Checkbox
woocommerce_wp_checkbox(
array(
'id' => '_roast_checkbox',
'label' => __('Roast Level', 'woocommerce'),
'description' => __('Enable roast level', 'woocommerce')
)
);
}
// Save Checkbox Field
add_action('woocommerce_process_product_meta', 'roast_custom_field_save');
function roast_custom_field_save($post_id) {
// Custom Product Checkbox Field
$roast_checkbox = isset($_POST['_roast_checkbox']) ? 'yes' : 'no';
update_post_meta($post_id, '_roast_checkbox', esc_attr($roast_checkbox));
}
/*---------------------------------------------------------------
*Display Select Box
---------------------------------------------------------------*/
add_action( 'woocommerce_before_add_to_cart_button', 'add_roast_custom_field', 0 );
function add_roast_custom_field() {
global $product;
// If is single product page and have the "roast_checkbox" enabled we display the field
if ( is_product() && $product->get_meta( '_roast_checkbox' ) === 'yes' ) {
echo '<div class="roast_select">';
$select = woocommerce_form_field( 'roast_custom_options', array(
'type' => 'select',
'class' => array('my-field-class form-row-wide'),
'label' => __('Roast Level'),
'required' => false,
'return' => false,
'options' => array(
'' => 'Please select',
'Blue' => 'Blue',
'Rare' => 'Rare',
'Medium Rare' => 'Medium Rare',
'Medium' => 'Medium',
'Medium Well' => 'Medium Well',
'Well Done' => 'Well Done'
)
), '' );
echo $select;
echo '</div>';
}
}
/*---------------------------------------------------------------
* Add as custom cart item data
---------------------------------------------------------------*/
add_filter( 'woocommerce_add_cart_item_data', 'add_custom_cart_item_data', 10, 21 );
function add_custom_cart_item_data($cart_item_data, $product_id, $variation_id ){
if( isset( $_POST['roast_custom_options'] ) ) {
$cart_item_data['roast_option'] = wc_clean( $_POST['roast_custom_options'] );
}
return $cart_item_data;
}
/*---------------------------------------------------------------
* Add custom fields values under cart item name in cart
---------------------------------------------------------------*/
add_filter( 'woocommerce_cart_item_name', 'roast_custom_field', 10, 21 );
function roast_custom_field( $item_name, $cart_item, $cart_item_key ) {
if( ! is_cart() )
return $item_name;
if( isset($cart_item['roast_option']) ) {
$item_name .= '<br /><div class="my-custom-class"><strong>' . __("Roast Level", "woocommerce") . ':</strong> ' . $cart_item['roast_option'] . '</div>';
}
return $item_name;
}
/*---------------------------------------------------------------
* Display roast custom fields values under item name in checkout
---------------------------------------------------------------*/
add_filter( 'woocommerce_checkout_cart_item_quantity', 'roast_custom_checkout_cart_item_name', 10, 21 );
function roast_custom_checkout_cart_item_name( $item_qty, $cart_item, $cart_item_key ) {
if( isset($cart_item['roast_option']) ) {
$item_qty .= '<br /><div class="my-custom-class"><strong>' . __("Roast Level", "woocommerce") . ':</strong> ' . $cart_item['roast_option'] . 'гр.</div>';
}
return $item_qty;
}
/*---------------------------------------------------------------
* Save chosen slelect 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_product_fitting_color', 10, 21 );
function save_order_item_product_fitting_color( $item, $cart_item_key, $values, $order ) {
if( isset($values['roast_option']) ) {
$key = __('Roast Level', 'woocommerce');
$value = $values['roast_option'];
$item->update_meta_data( $key, $value ,$item->get_id());
}
}
add_action('wp_footer','add_footer_script');
function add_footer_script(){
?>
<script>
jQuery('#roast_custom_options').on('change',function(){
var roast_level = jQuery(this).val();
/*console.log(roast_level); */
var button = jQuery(this).closest('form').find('.add_to_cart_button'); console.log(button);
jQuery(button).attr('data-roast_custom_options',roast_level);
});
</script>
<?php
}
I need to add the “Roast Level” selection form to the quick view window, to the
content-product-quick-view.php file.
When adding code, errors appeared. The form does not show, or the "Add to Cart" button disappears.
global $product;
// If is single product page and have the "roast_checkbox" enabled we display the field
if ( $product->get_meta( '_roast_checkbox' ) === 'yes' ) {
echo '<div class="roast_select">';
$select = woocommerce_form_field( 'roast_custom_options', array(
'type' => 'select',
'class' => array('my-field-class form-row-wide'),
'label' => __('Roast Level'),
'required' => false,
'return' => false,
'options' => array(
'' => 'Please select',
'Blue' => 'Blue',
'Rare' => 'Rare',
'Medium Rare' => 'Medium Rare',
'Medium' => 'Medium',
'Medium Well' => 'Medium Well',
'Well Done' => 'Well Done'
)
), '' );
echo $select;
echo '</div>';
}
As a result, I could not put this code in the php file. Perhaps here need to add additional code. And I ask for your help.
Change your script in add_footer_script with this:
( function( $ ) {
$( document ).ready( function() {
$(document).on('change', '#roast_custom_options' ,function() {
$('.add_to_cart_button').data('roast_custom_options', this.value)
});
});
}( jQuery ) );
if you are using ajax, you must subscribe via the parent container or document. To pass custom field using data attribute.
That template already has the variable product and and you're redeclaring it. Remove global $product from it the code you added to content-product-quick-view.php file and you should be good to go.

Add a drop down to product edit pages in product data "General" settings tab

I am trying to figure out how to modify the singe product options so the product admin can pick from the drop down list the condition of product, i.e. new/ used.
Below is a code that allows product admin to enter the condition of product manually.
// Enabling and Displaying Fields in backend
add_action( 'woocommerce_product_options_general_product_data', 'woo_add_custom_general_fields' );
function woo_add_custom_general_fields() {
global $woocommerce, $post;
echo '<div class="options_group">';
woocommerce_wp_text_input( array( // Text Field type
'id' => '_Stan',
'label' => __( 'Stan', 'woocommerce' ),
'placeholder' => 'i.e: nowa; uzywana...',
'desc_tip' => 'true',
'description' => __( 'Podaj stan plyty.', 'woocommerce' )
) );
echo '</div>'; // Closing </div> tag HERE
}
// Save Fields values to database when submitted (Backend)
add_action( 'woocommerce_process_product_meta', 'woo_save_custom_general_fields' );
function woo_save_custom_general_fields( $post_id ){
// Saving "Conditions" field key/value
$Stan_field = $_POST['_Stan'];
if( !empty( $Stan_field ) )
update_post_meta( $post_id, '_Stan', esc_attr( $Stan_field ) );
}
add_action('woocommerce_single_product_summary', 'woo_display_custom_general_fields_values', 45);
function woo_display_custom_general_fields_values() {
global $product;
echo '<p class="custom-Stan">Stan: ' . get_post_meta( $product->id, '_Stan', true ) . '</p>';
}
There is some errors and mistakes so I have revisited a little bit your code. Now you will have to replace woocommerce_wp_text_input() by woocommerce_wp_select() to get a select field instead, this way:
// Enabling and Displaying Fields in backend
add_action( 'woocommerce_product_options_general_product_data', 'woo_add_custom_general_fields' );
function woo_add_custom_general_fields() {
echo '<div class="options_group">';
woocommerce_wp_select( array( // Text Field type
'id' => '_Stan',
'label' => __( 'Stan', 'woocommerce' ),
'description' => __( 'Podaj stan plyty.', 'woocommerce' ),
'desc_tip' => true,
'options' => array(
'' => __( 'Select product condition', 'woocommerce' ),
'Nowa' => __('Nowa', 'woocommerce' ),
'Uzywana' => __('Uzywana', 'woocommerce' ),
)
) );
echo '</div>';
}
// Save Fields values to database when submitted (Backend)
add_action( 'woocommerce_process_product_meta', 'woo_save_custom_general_fields', 30, 1 );
function woo_save_custom_general_fields( $post_id ){
// Saving "Conditions" field key/value
$posted_field_value = $_POST['_Stan'];
if( ! empty( $posted_field_value ) )
update_post_meta( $post_id, '_Stan', esc_attr( $posted_field_value ) );
}
// Display In front end
add_action( 'woocommerce_product_meta_start', 'woo_display_custom_general_fields_values', 50 );
function woo_display_custom_general_fields_values() {
global $product;
// compatibility with WC +3
$product_id = method_exists( $product, 'get_id' ) ? $product->get_id() : $product->id;
echo '<span class="stan">Stan: ' . get_post_meta( $product_id, '_Stan', true ) . '</span>';
}
Code goes in function.php file of the active child theme (or active theme).
Tested and works.
Is better to avoid capitals in meta keys and they should start with an underscore.

Add a multilingual text after price in woocommerce_get_price_html hook

I am building an WooCommerce website and customizing it, copying and pasting code from internet libraries.
I have managed to add "custom price and custom text" in woocommerce product so they can be translated into different languages. Here is the look of the product page: https://www.primacent.de/de/product/woo-album-3-2
Here is my code in functions.php:
//New Price
add_action('woocommerce_product_options_pricing','custom_unit_price');
function custom_unit_price() {
woocommerce_wp_text_input( array( 'id' => '_unit_price', 'class' => 'wc_input_price short', 'label' => __( 'Unit Price', 'woocommerce' ) . ' ('.get_woocommerce_currency_symbol().')', 'type' => 'number', 'desc_tip' => 'true','description' => __( 'Enter the unit price if you want to show this price type.', 'woocommerce' ), 'custom_attributes' => array(
'step' => 'any',
'min' => '0'
) ) );
}
add_action('woocommerce_process_product_meta_simple', 'save_custom_unit_price');
function save_custom_unit_price($post_id) {
global $wpdb, $woocommerce, $woocommerce_errors;
update_post_meta( $post_id, '_unit_price', stripslashes( $_POST['_unit_price'] ) );
}
// Text Field for unit measurement
add_action('woocommerce_product_options_pricing','custom_unit_measurement');
function custom_unit_measurement() {
woocommerce_wp_text_input ( array('id' => '_unit_measurement', 'label' => __( 'Unit Measurement', 'woocommerce' ), 'placeholder' => 'i.e: pro Stück','desc_tip' => 'true','description' => __( 'Enter the unit measurement in your language. If you want to show price per unit, this field must be filled', 'woocommerce' )
)
);
}
add_action('woocommerce_process_product_meta_simple', 'save_custom_unit_measurement');
function save_custom_unit_measurement($post_id) {
global $wpdb, $woocommerce, $woocommerce_errors;
update_post_meta( $post_id, '_unit_measurement', stripslashes( $_POST['_unit_measurement'] ) );
}
// only copy the opening php tag if needed
// Change the shop / product prices if a _unit_price is set
function sv_change_product_html( $price_html, $product ) {
$_unit_price = get_post_meta( $product->id, '_unit_price', true );
if ( ! empty( $_unit_price ) ) {
$price_html = '<span class="amount">' . wc_price( $_unit_price ). ' </span>';
echo $_unit_measurement = get_post_meta( $product->id, '_unit_measurement', true );echo'<br />';
}
return $price_html;
}
add_filter( 'woocommerce_get_price_html', 'sv_change_product_html', 10, 2 );
The problem is that I want the unit measurement (_unit_measurement) after the unit price (_unit_price) to replace the hyphen mark '-'.
For some reasons, I can't put the second meta value into <span> wrap.
Please help me. How can I achieve this?
Thanks!
You just have to concatenate this unit measurement value inside a string (in a <span> tag for example) after the price using .= operator for $price_html variable before it's being returned.
So your code will be:
//New Price
add_action( 'woocommerce_product_options_pricing' ,'custom_unit_price' );
function custom_unit_price() {
woocommerce_wp_text_input( array(
'id' => '_unit_price',
'class' => 'wc_input_price short',
'label' => __( 'Unit Price', 'woocommerce' ) . ' ('.get_woocommerce_currency_symbol().')',
'type' => 'number',
'desc_tip' => 'true',
'description' => __( 'Enter the unit price if you want to show this price type.', 'woocommerce' ),
'custom_attributes' => array(
'step' => 'any',
'min' => '0'
)
));
}
add_action('woocommerce_process_product_meta_simple', 'save_custom_unit_price');
function save_custom_unit_price($post_id) {
global $wpdb, $woocommerce, $woocommerce_errors;
update_post_meta( $post_id, '_unit_price', stripslashes( $_POST['_unit_price'] ) );
}
// Text Field for unit measurement
add_action('woocommerce_product_options_pricing','custom_unit_measurement');
function custom_unit_measurement() {
woocommerce_wp_text_input ( array(
'id' => '_unit_measurement',
'label' => __( 'Unit Measurement', 'woocommerce' ),
'placeholder' => 'i.e: pro Stück',
'desc_tip' => 'true',
'description' => __( 'Enter the unit measurement in your language. If you want to show price per unit, this field must be filled', 'woocommerce' )
));
}
add_action('woocommerce_process_product_meta_simple', 'save_custom_unit_measurement');
function save_custom_unit_measurement($post_id) {
global $wpdb, $woocommerce, $woocommerce_errors;
update_post_meta( $post_id, '_unit_measurement', stripslashes( $_POST['_unit_measurement'] ) );
}
// only copy the opening php tag if needed
// Change the shop / product prices if a _unit_price is set
add_filter( 'woocommerce_get_price_html', 'sv_change_product_html', 10, 2 );
function sv_change_product_html( $price_html, $product ) {
$_unit_price = get_post_meta( $product->id, '_unit_price', true );
if ( ! empty( $_unit_price ) ) {
$_unit_measurement = get_post_meta( $product->id, '_unit_measurement', true );
// Here you just concatenate the $_unit_measurement variable (in for example another span tag) after the price
$price_html = '<span class="amount">' . wc_price( $_unit_price ). ' </span>';
$price_html .= '<span class="mesurement">' . $_unit_measurement . ' </span><br />';
}
// return the formated price with the formated unit mesurement
return $price_html;
}
Code goes in function.php file of your active child theme (active theme or in any plugin file).

Categories