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' );
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
That seemed to have done the trick! My issue is resolved now. Thank you!