1

I have added a custom field that is getting and displaying the value on the front-end. The issue arises when the field is empty or the value is 0, it shows empty on the front end. I want to display '0.00' instead of empty. Is there any switch statement that can go in the code? or what

function corecharge_woocommerce_display_product_attributes($product_attributes, $mproduct){
    $product_attributes['corecharge-field'] = [
        'label' => __('Core Charge', 'text-domain'),
        'value' => get_post_meta($mproduct->get_ID(), '_number_field', true),
    ];
//  echo var_dump($product_attributes);
    
    return $product_attributes;
    
}

Show 0.00 instead of empty on addition information tab

  • Since WooCommerce 3, you should use `get_meta()` method instead of WordPress `get_post_meta()` as WooCommerce is progressively migrating to custom database tables, for better performances. So replace `get_post_meta($mproduct->get_ID(), '_number_field', true),` with `$product->get_meta('_number_field'),`. – LoicTheAztec Sep 02 '23 at 00:35

1 Answers1

1

You can do this by handling the return value of get_post_metaWP-Function.

For example in your case turn it into your default value '0.00' in case it returns falsy:

get_post_meta($mproduct->get_ID(), '_number_field', true) ?: '0.00'
                                                          #########

The "switch statement or what" here is the ternary operator ?:Docs, with the middle part left out (its shorthand form).

This allows to have a default value with get_post_meta() when called for a single value (third parameter, $single, is true).

As it returns false if the post-meta is not found, the right-hand side, here the default value, is taken.

If the single post-meta field is set to an empty string "", the number zero or a string containing the number zero (e.g. "0"), it a is also falsy and the default value is taken.

Compare:

hakre
  • 193,403
  • 52
  • 435
  • 836
  • Thanks! It worked exactly how I wanted it to. Stackoverflow rocks :D – waleed ali mian Jul 18 '21 at 14:29
  • You're welcome, please upvote if you find it useful as well. Your question was borderline with existing content, but as far as I could see there was no default for get_post_meta() so far, so I added it. This is independent to woocommerce and works with any wordpress `get_post_meta()` and similar functions that can return `$single`. – hakre Jul 18 '21 at 14:33