Search code examples
phpwordpresswoocommercehook-woocommerce

How can I add a default value to custom field in addition information tab woocommerce


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


Solution

  • 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: