如何在附加信息选项卡 woocommerce 中为自定义字段添加默认值

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

我添加了一个自定义字段,用于在前端获取和显示值。当字段为空或值为0时出现问题,它在前端显示为空。我想显示“0.00”而不是空的。代码中是否有任何 switch 语句?或者什么

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

您可以通过处理 get_post_metaWP-Function 的 return 值来做到这一点。

例如在你的情况下把它变成你的默认值 '0.00' 以防它 returns falsy:

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

此处的“switch 语句或什么”是 ternary operator ?:Docs,中间部分被省略(其 shorthand 形式)。

这允许在为单个值调用时使用 get_post_meta() 的默认值(第三个参数,$single,是 true)。

因为 returns false 如果未找到 post-meta,则采用右侧,此处为默认值。

如果单个 post-meta 字段设置为空字符串 ""、数字零或包含数字零的字符串(例如 "0"),它是也 falsy 并采用默认值。

比较: