Skip to content

Instantly share code, notes, and snippets.

@hunsly
Last active October 15, 2023 09:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hunsly/6ca551008dc6ec4b3c2cd701ff29c01e to your computer and use it in GitHub Desktop.
Save hunsly/6ca551008dc6ec4b3c2cd701ff29c01e to your computer and use it in GitHub Desktop.
Wordpress WooCommerce Unit Price shortcode
<?php
/**
* Shortcode for product unit price.
*
* Example:
* [woo_product_unit_price unit="Kg" unit_ratio="0.25"]
*
* Frontend view:
* Egységár: 1000 Ft / Kg
*
* @param $atts
*
* @return string
*/
function woo_product_unit_price_shortcode( $atts ) {
$atts = shortcode_atts( array(
'unit' => null,
'unit_ratio' => null,
), $atts, 'woo_product_unit_price' );
if ( empty( $atts[ 'unit' ] ) or
empty( $atts[ 'unit_ratio' ] )
) {
return '';
}
global $product;
if ( ! $product ) {
return '';
}
$product_price = $product->get_price();
return '<div class="unit-price" data-product-price="'.$product_price.'" data-unit="'.$atts[ 'unit' ].'" data-unit-ratio="'.$atts[ 'unit_ratio' ].'">Egységár: ' . round(floatval($product_price) / floatval($atts[ 'unit_ratio' ])) . ' Ft/' . $atts[ 'unit' ] . '</div>';
}
add_shortcode( 'woo_product_unit_price', 'woo_product_unit_price_shortcode' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment