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

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路