简体   繁体   中英

Custom Shortcode displaying WooCommerce product price: Display a text for zero price

I'm using this code to show woocommerce products price

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' );

and shortcode:

[woocommerce_price id="99"]

I want to edit this code that if the price equals zero instead of zero show a custom message like "unavailable".

Try the following to display a custom text when price equals zero (replacing your code) :

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' );

Code goes in functions.php file of the active child theme (or active theme). Tested and works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM