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 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图2.0 版本点聚合中Marker的位置无法实时更新,如何解决呢?
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题