显示 WooCommerce 产品价格的自定义简码:显示零价格的文本

发布时间:2021-02-25 08:59

我正在使用此代码显示 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"]

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

回答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 文件中。经测试有效。