基于Woocommerce中产品价格的条件短码
问题描述:
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 ?
如果产品价格大于8美元,我试图制作一个打印“免费送货”的wordpress短代码,如果不是 返回空白(不打印任何内容)。 p>
function shortcode_FreeShipping($ product){
if($ product-> get_price()> 8){
return __( '免费送货','woocommerce');
}
其他{
返回__('','woocommerce');
}
}
add_shortcode('freeshipping','shortcode_FreeShipping');
code> pre>
当在产品页面上插入短代码 [freeshipping] code>时,页面无法加载。 p>
什么可能是错的? p>
div>
答
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"]