Skip Navigation

[Resolved] Blank number field is outputting a 0

This thread is resolved. Here is a description of the problem and solution.

Problem:

The code to add commas to the numbers to separate the thousands shows 0 when the result of the custom field is empty.

Solution:

Change the code to this:

add_shortcode( 'ts_format_number', 'ts_format_number_func');
function ts_format_number_func( $atts, $content ) {
    $int = (int) do_shortcode($content);
    if ($int == null) {
        return "";
    } else {
        return number_format($int, 0);
    }
     
}

100% of people find this useful.

This support ticket is created 3 years, 3 months ago. There's a good chance that you are reading advice that it now obsolete.

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

This topic contains 2 replies, has 2 voices.

Last updated by nateW 3 years, 3 months ago.

Assisted by: Christopher Amirian.

Author
Posts
#2290059

Tell us what you are trying to do?
I needed to add a comma to my outputted numbers. I followed the directions here for creating a shortcode (https://toolset.com/forums/topic/i-want-to-add-comma-every-three-digits/) and it works beautifully. However, now it outputs a zero if that same number field is blank. It doesn't do that if I don't use this custom shortcode. I imagine there's maybe a line to add to the shortcode php function code so that it doesn't output the zero if the field is blank, but not show how to do this. Any help would be appreciated!

Is there any documentation that you are following?
https://toolset.com/forums/topic/i-want-to-add-comma-every-three-digits/

functions.php code:
add_shortcode( 'ts_format_number', 'ts_format_number_func');
function ts_format_number_func( $atts, $content ) {
$int = (int) do_shortcode($content);
return number_format($int, 2);
}

Shortcode example:
[ts_format_number][types field="price"][/types][/ts_format_number]

With this shortcode, an empty "price" field outputs a zero now.

#2291057

Christopher Amirian
Supporter

Languages: English (English )

Hi there,

Please kindly change the first part of the code to:

add_shortcode( 'ts_format_number', 'ts_format_number_func');
function ts_format_number_func( $atts, $content ) {
    $int = (int) do_shortcode($content);
    if ($int == null) {
        return "";
    } else {
        return number_format($int, 0);
    }
    
}

Then, use the shortcode as you would do before.

Thanks.

#2291947

Worked like a dream 🙂 My issue is resolved now. Thank you!