Custom Static Fields Woocommerce Product Page - php

I wanted to add a Custom Field to WooCommerce. The field is supposed to be plain Text Field.
Then it should be displayed on the Frontend. Unfortunately, I didn’t find such a Text Field Code Snippet. But the Code below worked:
/**
* #snippet Display RRP/MSRP # WooCommerce Single Product Page
* #how-to Get CustomizeWoo.com FREE
* #author Rodolfo Melogli
* #compatible WooCommerce 5
* #donate $9 https://businessbloomer.com/bloomer-armada/
*/
// -----------------------------------------
// 1. Add RRP field input # product edit page
add_action( 'woocommerce_product_options_pricing', 'bbloomer_add_RRP_to_products' );
function bbloomer_add_RRP_to_products() {
woocommerce_wp_text_input( array(
'id' => 'rrp',
'class' => 'short wc_input_price',
'label' => __( 'RRP', 'woocommerce' ) . ' (' . get_woocommerce_currency_symbol() . ')',
'data_type' => 'price',
));
}
// -----------------------------------------
// 2. Save RRP field via custom field
add_action( 'save_post_product', 'bbloomer_save_RRP' );
function bbloomer_save_RRP( $product_id ) {
global $typenow;
if ( 'product' === $typenow ) {
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
if ( isset( $_POST['rrp'] ) ) {
update_post_meta( $product_id, 'rrp', $_POST['rrp'] );
}
}
}
// -----------------------------------------
// 3. Display RRP field # single product page
add_action( 'woocommerce_single_product_summary', 'bbloomer_display_RRP', 9 );
function bbloomer_display_RRP() {
global $product;
if ( $product->get_type() <> 'variable' && $rrp = get_post_meta( $product->get_id(), 'rrp', true ) ) {
echo '<div class="woocommerce_rrp">';
_e( 'RRP: ', 'woocommerce' );
echo '<span>' . wc_price( $rrp ) . '</span>';
echo '</div>';
}
}
The problem is that this Code is for Price. I needed something that is just plain Text, plus a few adjustments.
I want:
Title: PRODUCT YEAR
Field Type: Text Field
And when it is displayed, Title should be in Bold Font.
How can I make these happen?
Regards.

Related

Adding MSRP to product page for WooCommerce

I'm currently trying to add a new text-field to my product page. I want to display the MSRP price of my products next to the product. Like on the image below. The MSRP should be on where the red line is.
Here is the image
I've done quite a bit of research on the topic. There are a few plugins that would fix the problem. However most of them have either bad reviews or are paid. I've succesfully added a meta field for the MSRP. However when i add a price to this field it doesn't show up on the product page at all.
function bbloomer_display_RRP() {
global $product;
if ( $product->get_type() <> 'variable' && $rrp = get_post_meta( $product->get_id(), 'rrp', true ) )
{
echo '<div class="woocommerce_rrp">';
_e( 'RRP: ', 'woocommerce' );
echo '<span>' . wc_price( $rrp ) . '</span>';
echo '</div>';
}
}
The code above should display the MSRP price on the product page. However it doesn't
Regards,
Luuc
Are you adding bbloomer_display_RRP to any hook? The function by itself, won't do anything. Based on your screenshot, I would add it to the woocommerce_template_single_price hook with a priority of 5 so that it will appear just before the price does.
/**
* Add RRP Field to product data metabox
*/
function kia_add_RRP_to_products() {
woocommerce_wp_text_input( array(
'id' => 'rrp',
'class' => 'short wc_input_price',
'label' => __( 'RRP', 'woocommerce' ) . ' (' . get_woocommerce_currency_symbol() . ')',
'data_type' => 'price',
));
}
add_action( 'woocommerce_product_options_pricing', 'kia_add_RRP_to_products' );
/**
* Process, verify and save product data
*
* #param WC_Product $product
*/
function kia_save_RRP( $product ) {
if ( isset( $_POST['rrp'] ) ) {
$rrp = wc_format_decimal( wc_clean( wp_unslash( $_POST['rrp'] ) ) );
$product->update_meta_data( 'rrp', $rrp );
} else {
$product->delete_meta_data( 'rrp' );
}
}
add_action( 'woocommerce_admin_process_product_object', 'kia_save_RRP' );
/**
* Display RRP on front-end in product summary
*/
function kia_display_RRP() {
global $product;
$rrp = '10';
if ( ! $product->is_type( 'variable' ) ) {
$rrp = $product->get_meta( 'rrp', true );
if ( $rrp ) {
echo '<div class="woocommerce_rrp">';
printf( __( 'RRP: %s', 'your-textdomain' ), wc_price( $rrp ) );
echo '</div>';
}
}
}
add_action( 'woocommerce_single_product_summary', 'kia_display_RRP', 5 );

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:

Override woocommerce cart item price with product custom field value

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)

WooCommerce : add custom fields to product variations

I need help adding custom fields to my Product Variations and Simple Product pages. I tried using RemiCorson's info (http://www.remicorson.com/woocommerce-custom-fields-for-variations/), but I keep getting an error. I tried to duplicate what I saw in this user's posts for ISBN but it's not working for me.
The problem with the code below is that it doesn't show up on the live site. All help is greatly appreciated, I've spent most of today trying to figure out what I'm doing wrong.
Adding 6 custom text fields and 1 check box to both Simple Product and Variable Product pages in Woocommerce. These are not fields to be supplied (i.e. filled out) by the shopper, but rather custom information I want displayed on my product pages (and NOT within a tab).
// Display Fields
add_action( 'woocommerce_product_options_general_product_data', 'woo_add_custom_general_fields' );
// Save Fields
add_action( 'woocommerce_process_product_meta', 'woo_add_custom_general_fields_save' );
function woo_add_custom_general_fields() {
global $woocommerce, $post;
echo '<div class="options_group">';
// Custom fields will be created here...
// Text Field
woocommerce_wp_text_input(
array(
'id' => '_ISBN_field',
'label' => __( 'ISBN', 'woocommerce' ),
'placeholder' => '',
'desc_tip' => 'true',
'description' => __( 'ISBN.', 'woocommerce' )
)
);
function woo_add_custom_general_fields_save( $post_id ){
// Customer text ISBN Field
$woocommerce_text_field = $_POST['_ISBN_field'];
if( !empty( $woocommerce_text_field ) )
update_post_meta( $post_id, '_ISBN_field', esc_attr( $woocommerce_text_field ) );
else
update_post_meta( $post_id, '_ISBN_field', '' );
}
// Display Custom Field Value
echo get_post_meta( $post->ID, '_ISBN_field', true );
}
/* WooCommerce */
/* ----------------------------------------------------------------------------------- */
/* Start WooThemes Functions - Please refrain from editing this section */
/* ----------------------------------------------------------------------------------- */
I have never needed to bother with woocommerce_product_after_variable_attributes_js, you just need to add the input and then deal with saving it.
Another thing that has changed since Remi's article was published is that the WooCommerce variation meta data is no longer printed in a <Table> element... and is now a <div> element. This is important for how you structure your new content.
Here's is how you'd add a meta field to a variation:
// regular variable products
add_action( 'woocommerce_product_after_variable_attributes', 'add_to_variations_metabox', 10, 3 );
add_action( 'woocommerce_save_product_variation', 'save_product_variation', 20, 2 );
/*
* Add new inputs to each variation
*
* #param string $loop
* #param array $variation_data
* #return print HTML
*/
function add_to_variations_metabox( $loop, $variation_data, $variation ){
$custom = get_post_meta( $variation->ID, '_custom', true ); ?>
<div class="variable_custom_field">
<p class="form-row form-row-first">
<label><?php echo __( 'Custom Data:', 'plugin_textdomain' ); ?></label>
<input type="text" size="5" name="variation_custom_data[<?php echo $loop; ?>]" value="<?php echo esc_attr( $custom ); ?>" />
</p>
</div>
<?php
}
/*
* Save extra meta info for variable products
*
* #param int $variation_id
* #param int $i
* return void
*/
function save_product_variation( $variation_id, $i ){
// save custom data
if ( isset( $_POST['variation_custom_data'][$i] ) ) {
// sanitize data in way that makes sense for your data type
$custom_data = ( trim( $_POST['variation_custom_data'][$i] ) === '' ) ? '' : sanitize_title( $_POST['variation_custom_data'][$i] );
update_post_meta( $variation_id, '_custom', $custom_data );
}
}
I have found the following code from here working with WooCommerce 4.8.0
/**
* Create new fields for variations
*
*/
function hrx_variation_settings_fields( $loop, $variation_data, $variation ) {
// Text Field
woocommerce_wp_text_input(
array(
'id' => 'isbn_field[' . $variation->ID . ']',
'label' => __( 'ISBN', 'texdomain' ),
'placeholder' => '',
'desc_tip' => 'true',
'description' => __( 'ISBN', 'texdomain' ),
'value' => get_post_meta( $variation->ID, 'isbn_field', true )
)
);
}
add_action( 'woocommerce_product_after_variable_attributes', 'hrx_variation_settings_fields', 10, 3 );
/**
* Save new fields for variations
*
*/
function hrx_save_variation_settings_fields( $post_id ) {
// Text Field
$isbn_value = $_POST['isbn_field'][ $post_id ];
if( ! empty( $isbn_value ) ) {
update_post_meta( $post_id, 'isbn_field', esc_attr( $isbn_value ) );
}
}
add_action( 'woocommerce_save_product_variation', 'hrx_save_variation_settings_fields', 10, 2 );
WooCommerce : add custom fields to product variations

Wordpress Custom Fields

I'm new to PHP, so this is confusing me a little. I'm using the Woocommerce plugin for Wordpress and I'm trying to add a custom field to display rental prices for certain products. However, not all products have a rental option, so I want this to only display on products that I give a rental price.
Here's the code I'm using, which works fine. The only problem is that it displays a rental price of $0 on products I haven't specified a rental price. Instead of display $0, I just want it to not display at all.
//add rental field
add_action( 'woocommerce_product_options_pricing', 'wc_rent_product_field' );
function wc_rent_product_field() {
woocommerce_wp_text_input( array( 'id' => 'rent_price', 'class' => 'wc_input_price short', 'label' => __( 'rent', 'woocommerce' ) . ' (' . get_woocommerce_currency_symbol() . ')' ) );
}
//save rental field
add_action( 'save_post', 'wc_rent_save_product' );
function wc_rent_save_product( $product_id ) {
// If this is a auto save do nothing, we only save when update button is clicked
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return;
if ( isset( $_POST['rent_price'] ) ) {
if ( is_numeric( $_POST['rent_price'] ) )
update_post_meta( $product_id, 'rent_price', $_POST['rent_price'] );
} else delete_post_meta( $product_id, 'rent_price' );
}
//display rental field
add_action( 'woocommerce_single_product_summary', 'wc_rent_show', 5 );
function wc_rent_show() {
global $product;
// Do not show this on variable products
if ( $product->product_type <> 'variable' ) {
$rent = get_post_meta( $product->id, 'rent_price', true );
echo '<div class="woocommerce_msrp">';
_e( 'Rent: ', 'woocommerce' );
echo '<span class="woocommerce-rent-price">' . woocommerce_price( $rent ) . '</span>';
echo '</div>';
}
}
Can anyone help with this? I've searched around the internet looking for an answer, but it seems to be going over my head.
if ( $product->product_type <> 'variable' ) {
$rent = get_post_meta( $product->id, 'rent_price', true );
if($rent)>0
{
echo '<div class="woocommerce_msrp">';
_e( 'Rent: ', 'woocommerce' );
echo '<span class="woocommerce-rent-price">' . woocommerce_price( $rent ) . '</span>';
echo '</div>';
}
}
This was exactly what I was looking for and after a little tweaking to the above answer the following code displays an annual rental price only for products with a rental price. It also orders the rental price to display after the RRP and discount prices on both the single product and archive pages.
//add rental field
add_action( 'woocommerce_product_options_pricing', 'wc_rent_product_field' );
function wc_rent_product_field() {
woocommerce_wp_text_input( array( 'id' => 'rent_price', 'class' => 'wc_input_price short', 'label' => __( 'Annual Rental', 'woocommerce' ) . ' (' . get_woocommerce_currency_symbol() . ')' ) );
}
//save rental field
add_action( 'save_post', 'wc_rent_save_product' );
function wc_rent_save_product( $product_id ) {
// If this is a auto save do nothing, we only save when update button is clicked
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return;
if ( isset( $_POST['rent_price'] ) ) {
if ( is_numeric( $_POST['rent_price'] ) )
update_post_meta( $product_id, 'rent_price', $_POST['rent_price'] );
} else delete_post_meta( $product_id, 'rent_price' );
}
//display rental field
add_action( 'woocommerce_single_product_summary', 'wc_rent_show', 20 );
function wc_rent_show() {
global $product;
// Do not show this on variable products
if ( $product->product_type <> 'variable' ) {
$rent = get_post_meta( $product->id, 'rent_price', true );
if ($rent > 0) {
echo '<div class="woocommerce_msrp">';
_e( 'Annual Rental: ', 'woocommerce' );
echo '<span class="woocommerce-rent-price">' . woocommerce_price( $rent ) . '</span>';
echo '</div>';
}
}
}
// Optional: To show on archive pages
add_action( 'woocommerce_after_shop_loop_item_title', 'wc_rent_show', 50 );

Categories