Im trying to make a wordpress shortcode that print "Free Shipping" if product price is greater than 8$, if not returns blank (prints nothing).
function shortcode_FreeShipping( $product ) {
if( $product->get_price() > 8 ) {
return __( 'Free Shipping', 'woocommerce' );
}
else {
return __( '', 'woocommerce' );
}
}
add_shortcode('freeshipping', 'shortcode_FreeShipping');
When shortcode [freeshipping]
in inserted on product page, the page doesn't load.
What could be wrong ?
Try this instead where $product
(the WC_Product
object instance) is correctly called:
function shortcode_freeshipping( $atts ) {
// Only on single product pages
if( ! is_product() ) return;
// Shortcode attributes
$atts = shortcode_atts( array(
'price' => 8 // HERE you set your default price
), $atts, 'freeshipping' );
global $product;
if( ! is_object($product) )
$product = wc_get_product( get_the_id() );
if( $product->get_price() > $atts['price'] ) {
return __( 'Free Shipping', 'woocommerce' );
} else {
return __( '', 'woocommerce' );
}
}
add_shortcode('freeshipping', 'shortcode_freeshipping');
Code goes in function.php file of your active child theme (or active theme). Tested and works.
USAGE - 2 possibilities:
1) With the default defined price:
[freeshipping]
2) With a custom price (using the price
argument):
[freeshipping price="10"]