基于 Woocommerce 中产品价格的条件短代码

问题描述 投票:0回答:1

我正在尝试制作一个 WordPress 短代码,如果产品价格大于 8 美元,则打印“免费送货”,否则返回空白(不打印任何内容)。

function shortcode_FreeShipping( $product ) {
  if( $product->get_price() > 8 ) {
     return __( 'Free Shipping', 'woocommerce' );
  }
  else {
     return __( '', 'woocommerce' );
  }
}
add_shortcode('freeshipping', 'shortcode_FreeShipping');

当短代码

[freeshipping]
插入产品页面时,页面不会加载。

可能出了什么问题?

php wordpress woocommerce shortcode product-price
1个回答
1
投票

尝试使用此方法来正确调用

$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"]
© www.soinside.com 2019 - 2024. All rights reserved.