drm16022 2018-05-19 23:31
浏览 33
已采纳

基于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 ?

  • 写回答

1条回答 默认 最新

  • dqrfdl5708 2018-05-20 03:47
    关注

    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"]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀