Skip Navigation

[Resolved] Number Field Comma – Error when using custom shortcode

This support ticket is created 2 years, 10 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.

Sun Mon Tue Wed Thu Fri Sat
- 9:00 – 12:00 9:00 – 12:00 9:00 – 12:00 9:00 – 12:00 9:00 – 12:00 -
- 13:00 – 18:00 13:00 – 18:00 13:00 – 18:00 14:00 – 18:00 13:00 – 18:00 -

Supporter timezone: America/Jamaica (GMT-05:00)

This topic contains 2 replies, has 2 voices.

Last updated by nateW 2 years, 10 months ago.

Assisted by: Shane.

Author
Posts
#2418401

Hello, I followed your previous help article on adding a custom shortcode that will add commas to a number field (https://toolset.com/forums/topic/comma-format/). It works great, except when that field is blank. It's a real estate site, so if a property is coming soon and it doesn't have the price field filled in yet for example, it will show the error above the results:

Warning: number_format() expects parameter 1 to be float, string given in

From what I understand, I believe that I need to maybe assign 0 when no number is put into a variable or wrap it in a conditional statement to ignore it when no variable exists. How can I go about tweaking that shortcode to do this?

Here is the PHP code that I'm using from that previous article listed above:
// Add Shortcode
function wp_format_number( $atts ) {

// Attributes
$atts = shortcode_atts(
array(
'number' => '',
),
$atts
);

return number_format($atts['number'],0,'.',',');

}
add_shortcode( 'wp_format_number', 'wp_format_number' );

#2418561

Shane
Supporter

Languages: English (English )

Timezone: America/Jamaica (GMT-05:00)

Hi Nate,

What you can do is add a conditional for in the code to account for when the field is empty.

// Add Shortcode
function wp_format_number( $atts ) {

// Attributes
$atts = shortcode_atts(
array(
'number' => '',
),
$atts
);
$number = '';
if(!empty($atts['numer'])){
$number = number_format($atts['number'],0,'.',',');
}
return $number;

}
add_shortcode( 'wp_format_number', 'wp_format_number' );

Please let me know if this updated shortcode works.

Thanks,
Shane

#2420099

That seemed to have done the trick! My issue is resolved now. Thank you!