display item price (not item total) in woocommerce emails - wordpress

I need to display the item price in emails sent to admin and to customers using WooCommerce.
The default templates display Item, Quantity, and Price (item price X quantity). I can add the columns to the tables, but don't know how to get the data from the product.
(It is interesting that this has not been included in the default. I dont think i've ever placed an order online that did not include the single item price.)
This post was helpful, but didn't give me quite all needed:
display tax in woocommerce invoice

It has been a while but this may come handy to someone else.
As far as I am aware, there is no method that returns the unit price, but you can just calculate it by dividing the total price of the item by its quantity like so:
$item->get_total() / $item->get_quantity()
Since this will return just a number, you would probably want to add a currency symbol, so, you would end up with something like this:
<?php echo wc_price($item->get_total() / $item->get_quantity()); ?>

I edited plugins/woocommerce/templates/emails/email-order-items.php
After product name I inserted the price:
<br/>
<strong><?php _e( 'Price', 'woocommerce' ); ?>:</strong>
<?php echo apply_filters( 'woocommerce_cart_item_price', WC()->cart->get_product_price( $_product ), $cart_item, $cart_item_key ); ?>
NB! I put my custom files in directory mytheme/woocommerce/emails/ - without "templates" folder (!). Strange but it's the only way to force them working.

Looks like #Anunja's code up above may no longer work - instead just add the following line underneath Product Name in a copied version of templates/emails/email-order-items.php
echo '<br/>Individual Price $' . $_product->get_price();

Related

Math Calculation with Woocommerce Product Price Field

I am working with Woocommerce and Advanced Custom Fields.
I would like to divide the Woocommerce product price by a custom field and then output this as another custom field so it can be shown on the product page.
Example would be a pack of 10 pens, where I also want to show the cost-per-pen as a custom field, allowing customers to compare the price-per-unit across multiple skus.
I believe you could do something simple like:
<?php
$price = $product->get_price_html();
$customfield = get_field('myfield');
// simple maths
$price_piece = $price / $customfield;
?>
<div>
<?php echo $price_piece ;?>
</div>
There is also a helpful page for woocommerce product information
https://www.businessbloomer.com/woocommerce-easily-get-product-info-title-sku-desc-product-object/. I didnt checked the code, but you get the idea, hope that helps!

How to display rounded price incl. tax with comma from their WooCommerce Product ID/Variation ID?

I'm trying to display prices of certain WooCommerce products/variations on a regular page. The reason I can't type it manually is these prices are changed in real-time by a plugin with a currency rate.
I found this page:
How to get the price of variable product using variation ID?
In my page builder I inserted a code block with this piece of code:
<?PHP
$product_id = ###;
// ### is the product ID
$_product = wc_get_product( $product_id );
echo $_product->get_sale_price();
?>
or this one
<?PHP
$variation_id = ###;
// ### is the variation ID
$_variation = wc_get_product( $variation_id );
echo $_variation->get_sale_price();
?>
They both worked but the displayed numbers had so many decimal places like 2360.8353159978.
(see example screenshot: https://i.imgur.com/7D4Xydu.png)
I would like to round them up to zero like 2360.
The other issue is they are with no tax. I think that's because I use the price excl. tax on the backend of product pages (Woo shows the price incl. tax on the front end though, which is what I want to achieve here too).
The third issue is numbers don't the comma for thousands.
The perfect result should be 2,596 because 2,360 + 10% tax = 2,596
I'm very new to PHP and have sought the answer for a long time.
Can anybody kindly give me some suggestions? Any input is appreciated.
I'm not sure about the tax, but here is the solution for trimming the decimals:
/** Trim zeros in price decimals **/
add_filter( 'woocommerce_price_trim_zeros', '__return_true' );
add_filter( 'woocommerce_adjust_non_base_location_prices', '__return_false' );
I've found the answer to my own question. See the codes below:
<?PHP
$variation_id = ###;
$_variation = wc_get_product( $variation_id );
echo wc_price($_variation->get_price_including_tax(), array('decimals' => 0));
?>
You can replace the variation_id with product_id too as long as you can find them.
So I needed to use the wc_price to get the formatted price numbers, which is the way you set the thousand separator and no. of decimal, etc in WooCommerce' General tab. For rounding, since I've created a way to round the numbers in WooCommerce (similar to function.php in the child theme) so wc_price will call and show the rounded result as well.
The format still needs to be tweaked on my WordPress page e.g. I like to remove all decimals so I used array('decimals' => 0) to truncate them.
Text style also needs to be fixed with CSS but I'm not to show that here since it's not relevant to the topic.
Anyway the problem is solved. Hope this code is useful to other people. Again I know very very little about PHP it's just from my searching on Google. Anyone who likes to improve the code please share.
Best,
Acon

How to get a Product Variation Custom Field to work along other plugins?

I get this code (see below) to create a Product Variation Custom Field. It works just fine. Now I need to use the WP All Import Pro plugin to import Products from a csv file. This plugin allow to create the importation task by mapping the information in the csv to the fields of Product and Product Variation.
Problem: thing is that the new created Product Variation Custom Field is not visible for the WP All Import plugin. I mean, this new field is not listed when I do the mapping of the data be imported.
My assumption is that this code fails to create some data in the database to make this field available for other module.
How can I get this to work properly
I also attached a capture of the WP All Import page where the field should be visible.
/*******************************
add custom fields to product variations
*********************************/
// 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 __( 'MY CUSTOM FIELD:', '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 );
}
}
WP ALL IMPORT has this section coded into their files. They have not provide any hook or filter to add fields to this section.
The most important thing here is that WP ALL IMPORT has thought is like this :
As all the Meta for a particular variation is added finally to the post meta table. Which will be retrieved as by get_post_meta. Just like the custom fields. So in order to attach meta to the variation, you can just another Custom Fields with the Name as the name which the actual meta is stored with and with the value you want the variation to be. Just check the image attached. Refer - http://www.wpallimport.com/documentation/custom-fields/theme-plugin-fields/
I know this question was asked almost a year ago but I have been trying to figure out this exact issue out for quite some time now. But in the end I managed to find a workaround that at least will allow you to get that data into the variation instead of the main parent product:
1) In the WpAllImport Wordpress Addon you will be able to see a "variations" tab as shown in your screenshot. Click on this.
2) On this page you will once again not be able to see any custom fields you have made for variations HOWEVER there is a product attributes section.
3) If you add your variation as an attribute and uncheck "Show in variations" and "Taxonomy" and "Is Visible" then you can store your data in an attribute.
4) After the import you should be able to see you data in the attribute, if you know some programming you can even write a script to then loop through all variations and copy this data over to a custom field.
I know it's not much, but for my purposes I was at least able to save the data in the variation which I then used late in a product export plugin.
Hope that helps!
Though this question was initially asked 2 years ago. I found a solution in 2020. I hope this will help anyone who's still looking for a solution.
Please go to All Products and at the top where it says Add New Product you should see two more buttons "Import" and "Export". Click on Export and you will see an option of checkbox "Yes, export all custom meta" Please check this potion and all your custom fields even in variations will be exported.
Thanks

Display additional product information (e.g. image caption) when hovering product image

I'm using using the WooCommerce plugin for WordPress to display my products. The thing is, when you are viewing the product category (archive), you can see the product name, image and price, but that doesn't really say all that much about exactly what the product is.
What I would like is for some more information to become available when you hover the product images. Something a bit like this.
Would it be possible to retrieve some of the information about the image, that I can enter in the WordPress media libray: title, caption alt text or description?
You can check the webshop here.
EDIT:
I found that editing the content-product.php file in the WooCommerce plugin folder, if I put this:
?>
random text
<?php
somewhere inside the php tags in the <li> section of that file, I could get 'random text' to show either above or below the product image on the product archive page. So, if I could replace that with a function that would retreive for instance the product image caption or some custom field that I can fill out for each product, that would go a long way towards solving the issue.
So, if anyone knows of a function that does this, please share it here.
hello sir just use this plugin
https://wordpress.org/plugins/woocommerce-custom-product-data-fields/
for retrieving any costume fields do like this
Retrieving multiselect value
global $wc_cpdf;
$multiselect = $wc_cpdf->get_value($post->ID, '_mymultiselect');
foreach ($multiselect as $value) {
echo $value;
}
Retrieving image value
global $wc_cpdf;
$image_id = $wc_cpdf->get_value($post->ID, '_myimage');
$size = 'thumbnail';
$image_attachment = wp_get_attachment_image($image_id, $size);
echo $image_attachment;
}
I recently did this with a website for a client. I changed the hover text for each product from "Add to Cart" to the product short description. Here is my code:
add_filter( 'woocommerce_product_add_to_cart_text', 'woo_archive_custom_cart_button_text' ); // 2.1 +
function woo_archive_custom_cart_button_text() {
//get the product object
global $product;
$id = $product->get_id();
$descript = $product->get_short_description();
//take out html from description
$descript1 = strip_tags($descript);
//shorten description length to fit the product image box
if (strlen($descript1) > 100){
$descript1 = substr($descript1, 0, 99) . '...';
}
return __( $descript1, 'woocommerce' );
}

Wordpress shortcode linked to another DB

First thing first, this is my first shortcode attempt.
It is worthed mention that I'm also using woocommerce on my website.
Let's start:
I know that to add shortcodes into wordpress, you need to write something similar to the code below into the functions.php file: (this is just an example)
function myshortcode() {
return "This is a shortcode example!";
}
add_shortcode( 'mycode', 'myshortcode' );
and if i add [mycode] into the wordpress page editor, the preview shows my text correctly.
But what if i need to use a variable (in my case woocommerce order number) in the shortcode?
Let's say i need to compare woocommerce_order_number with my_custom_uid (inserted into another database, outside wordpress).
I usually use a db request like the one below, and usually it works fine (as before, this is only an example):
select 'my_custom_uid' from 'my_custom_database' where 'woocommerce_order_number' = '1234'
The problem is that i don't know the woocommerce_order_number (it changes everytime!), because this shortcode needs to go inside an html email body i need to send out to customers after they placed the order.
How can i get the customer woocommerce order (variable that changes everytime) so that i will be able to use it into my shortcode to link it to my custom_uid?
If the question is not clear enough, please feel free to ask for clarification!
thanks a lot
I don't see a reason to use a shortcode. If you want to add something to an email, you should use one of the hooks in the email. For example:
function kia_display_email_order_meta( $order, $sent_to_admin, $plain_text ) {
$some_field = get_post_meta( $order->id, '_some_field', true ),
$another_field = get_post_meta( $order->id, '_another_field', true ),
if( $plain_text ){
echo 'The value for some field is ' . $some_field . ' while the value of another field is ' . $another_field;
} else {
echo '<p>The value for <strong>some field</strong> is ' . $some_field. ' while the value of <strong>another field</strong> is ' . $another_field . '</p>';
}
}
add_action('woocommerce_email_customer_details', 'kia_display_email_order_meta', 30, 3 );
Note that the $order object is the first parameter available to the kia_display_email_order_meta function. So you'd be able to get the ID via $order->id. This should add the data after the customer address details, but there are other hooks available if woocommerce_email_customer_details isn't appropriate.
I finally managed to solve this, and here's what i did if someone is interested:
<?PHP
add_action('fue_before_variable_replacements', 'register_variable_replacements', 11, 4);
add_action('fue_email_variables_list', 'email_variables_list');
/**
* This gets called to replace the variable in the email with an actual value
* #param $var - Modify this: array key is the variable name, value is the replacement
*/
function register_variable_replacements($var, $email_data, $queue_item, $email){
global $wpdb;
// Look up UID from order number
$orderNumber = $var->get_variables()['order_number'];
$sql = " //Your sql statement here...//";
$results = $wpdb->get_results($sql);
$UID = $results[0]->meta_value;
$variables = array(
'uid' => $UID
);
$var->register($variables);
}
function email_variables_list($email)
{
global $woocommerce;
?>
<li class="var hideable var_subscriptions">
<strong>{uid}</strong>
<img class="help_tip" title="<?php _e('Order UID', 'follow_up_emails'); ?>" src="<?php echo $woocommerce->plugin_url(); ?>/assets/images/help.png" width="16" height="16"/>
</li>
<?php
}
Now on your follow up email plugin, you can use {uid} as a variable and this will be replaced with the correct value on every email.
I though the best way was to use short code, but then i discovered this filter and i think this is the best way to handle this. This code is also pretty flexible and you can add as many variables as you want.
Hope this can help someone.

Resources