IN WooCommerce I am using the code of this tread to display with a short code the product prices from a defined product ID. But it don't really do what I want. Here is that code:
function so_30165014_price_shortcode_callback( $atts ) {
$atts = shortcode_atts( array(
'id' => null,
), $atts, 'bartag' );
$html = '';
if( intval( $atts['id'] ) > 0 && function_exists( 'wc_get_product' ) ){
$_product = wc_get_product( $atts['id'] );
$number = number_format($_product->get_price(), 2, '.', ',');
$html = "$" . $number;
}
return $html;
}
add_shortcode( 'woocommerce_price', 'so_30165014_price_shortcode_callback' );
I have a poor knowledge in php coding. But I've seen that there this other thread to display product prices:
$_product->get_regular_price();
$_product->get_sale_price();
$_product->get_price();
I Have tried to mix these code into the big code, and replaced get_price()
… It works, but what I want is to display prices is something like this :
So the Regular price crossed out, and the Sale price next to it, like in this screenshot. If there is no Sale price, it display only the regular price.
Also I have some other problems:
I need to display the price is in
€
, not in$
, so I have replaced the currency symbol from$
(dollars) to€
(euros) with this code:$html = "€" . $number;
I need to display the currency symbol after the price, like :
37 €
(with a blank space between), not like$37
.
How can I make it work in a clean normal way?
An alternative, if anyone needs simple text output of prices, is the following:
The shortcode is then
[product_price id=XX]
(replacing XX with the product id)To add styling to the price, add a span class by adding the line:
$html .= "<span class="price_by_id_shortcode">". $price . "</span>";
,change the line
return $price;
toreturn $html;
,then add your style formatting to your css as needed.
(N.B. this only outputs current price, not regular price.)
OK, a friend of me helped me, and gave me the good code. If it help someone else ... Here it is:
bye !
Updated (takes into account if your prices are displayed with or without taxes)
With Woocommerce there is already formatting price function
wc_price()
that you can use in your code. Also you need to get the sale price…To get this working when there is a sale price or without it try this code (commented):
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
USAGE (for example product ID
37
):This code is tested and works. You will get this: