【问题标题】:How can I add a default value to custom field in addition information tab woocommerce如何在附加信息选项卡 woocommerce 中向自定义字段添加默认值
【发布时间】:2021-07-18 13:50:15
【问题描述】:

我添加了一个自定义字段,用于在前端获取和显示值。当字段为空或值为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

【问题讨论】:

    标签: php wordpress woocommerce hook-woocommerce


    【解决方案1】:

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

    例如,在您的情况下将其转换为默认值 '0.00',以防它返回 falsy

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

    这里的“switch statement or what”是ternary operator ?:Docs,中间部分省略(它的简写形式)。

    这允许在调用单个值时使用get_post_meta() 的默认值(第三个参数$singletrue)。

    如果找不到后元,则返回false,因此采用右侧,这里是默认值。

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

    比较:

    【讨论】:

    • 谢谢!它完全按照我想要的方式工作。 Stackoverflow 岩石:D
    • 不客气,如果你觉得它也有用,请点赞。您的问题与现有内容接近,但据我所知,到目前为止 get_post_meta() 没有默认值,所以我添加了它。这独立于 woocommerce 并适用于任何 wordpress get_post_meta() 和可以返回 $single 的类似函数。
    猜你喜欢
    • 2018-09-12
    • 2021-06-28
    • 2021-02-03
    • 1970-01-01
    • 2018-05-21
    • 2017-12-30
    • 1970-01-01
    • 2018-03-25
    • 1970-01-01
    相关资源
    最近更新 更多