【问题标题】:Conditional shortcode based on product price in Woocommerce基于 Woocommerce 中产品价格的条件短代码
【发布时间】:2018-10-30 00:29:16
【问题描述】:

我正在尝试制作一个 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 price


    【解决方案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"]
    

    【讨论】:

    • 像魅力一样工作,非常感谢。自定义价格参数也非常有用:)
    猜你喜欢
    • 1970-01-01
    • 2021-05-19
    • 2019-12-25
    • 2021-08-01
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 2013-08-07
    • 1970-01-01
    相关资源
    最近更新 更多