Woocommerce 中基于产品价格的条件简码
Conditional shortcode based on product price in Woocommerce
我正在尝试制作一个 wordpress 短代码,如果产品价格大于 8 美元,则打印 "Free Shipping",否则 returns 为空白(不打印任何内容)。
function shortcode_FreeShipping( $product ) {
if( $product->get_price() > 8 ) {
return __( 'Free Shipping', 'woocommerce' );
}
else {
return __( '', 'woocommerce' );
}
}
add_shortcode('freeshipping', 'shortcode_FreeShipping');
当在产品页面上插入短代码 [freeshipping]
时,页面不会加载。
有什么问题吗?
在正确调用 $product
(WC_Product
对象实例)的地方试试这个:
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');
代码进入您的活动子主题(或活动主题)的 function.php 文件。已测试并有效。
用法 - 2 种可能性:
1) 默认定义价格:
[freeshipping]
2) 使用自定义价格(使用 price
参数):
[freeshipping price="10"]
我正在尝试制作一个 wordpress 短代码,如果产品价格大于 8 美元,则打印 "Free Shipping",否则 returns 为空白(不打印任何内容)。
function shortcode_FreeShipping( $product ) {
if( $product->get_price() > 8 ) {
return __( 'Free Shipping', 'woocommerce' );
}
else {
return __( '', 'woocommerce' );
}
}
add_shortcode('freeshipping', 'shortcode_FreeShipping');
当在产品页面上插入短代码 [freeshipping]
时,页面不会加载。
有什么问题吗?
在正确调用 $product
(WC_Product
对象实例)的地方试试这个:
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');
代码进入您的活动子主题(或活动主题)的 function.php 文件。已测试并有效。
用法 - 2 种可能性:
1) 默认定义价格:
[freeshipping]
2) 使用自定义价格(使用 price
参数):
[freeshipping price="10"]