questions

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

Rate this post

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”.

 

✔️Solution:

 

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.

Leave a Reply

Your email address will not be published.

Back to top button