【问题标题】:Custom Shortcode displaying WooCommerce product price: Display a text for zero price显示 WooCommerce 产品价格的自定义简码:显示零价格文本
【发布时间】:2021-02-25 08:59:48
【问题描述】:

我正在使用此代码显示 woocommerce 产品价格

function so_30165014_price_shortcode_callback( $atts ) {
    $atts = shortcode_atts( array(
        'id' => null,
    ), $atts, 'bartag' );
    
    $html = '';
    
    if( intval( $atts['id'] ) > 0 && function_exists( 'wc_get_product' ) ){
        $_product = wc_get_product( $atts['id'] );
        $number = number_format($_product->get_price(), 0, '.', ',');
        $html = "$" . $number;
     }
     return $html;
}

add_shortcode( 'woocommerce_price', 'so_30165014_price_shortcode_callback' );

和简码:

[woocommerce_price id="99"]

我想编辑此代码,如果价格等于零而不是零,则显示自定义消息,例如“不可用”。

【问题讨论】:

    标签: php wordpress woocommerce shortcode price


    【解决方案1】:

    尝试以下操作以在价格为零时显示自定义文本(替换您的代码)

    function wc_price_shortcode_callback( $atts ) {
        extract( shortcode_atts( array(
            'id' => null,
        ), $atts, 'woocommerce_price' ) );
        
        if( intval( $id ) > 0 && function_exists( 'wc_get_product' ) ){
              $product = wc_get_product( $id );
              
              if ( $product->get_price() > 0 ) {
                  return $product->get_price_html();
              } else {
                  return __( "Price unavailable", "woocommerce" );
              }
         }
    }
    add_shortcode( 'woocommerce_price', 'wc_price_shortcode_callback' );
    

    代码位于活动子主题(或活动主题)的functions.php 文件中。经过测试并且可以工作。

    【讨论】:

    • 谢谢。我必须将您的所有代码而不是第一个代码添加到函数文件中吗?对不起。我是 WordPress 世界的新手。
    • 当我想保存function.php文件时:语法错误,意外';',期待','或')'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-24
    • 1970-01-01
    • 2017-11-24
    • 2018-04-23
    • 2021-04-29
    • 1970-01-01
    • 2021-02-04
    相关资源
    最近更新 更多