如何将自定义字段添加到 WooCommerce 设置中的 "Products Inventory" 选项卡?

How do I add a custom field to the "Products Inventory" tab in the WooCommerce settings?

我正在寻找一种方法来将新字段添加到 WooCommerce - 设置 - 产品 - 库存

见附图:


经过一些研究,我认为我应该使用 woocommerce_inventory_settings 过滤器挂钩,但我没有立即想到如何在实践中应用它?

woocommerce_inventory_settings 挂钩可以在 class-wc-settings-products.php on line 81

中找到(在 WooCommerce 4.4.1 中)

所以你可以使用

// Add custom field: WooCommerce > Settings > Products > Iventory
function filter_woocommerce_inventory_settings( $settings ) {
    $settings[] = array(
        'title' => __( 'My title', 'woocommerce' ),
        'type'  => 'title',
        'desc'  => '',
        'id'    => 'product_inventory_custom_options',
    );
    
    $settings[] = array(
        'title'       => __( 'My message', 'woocommerce' ),
        'id'          => 'woocommerce_my_message',
        'type'        => 'text',
        'default'     => '',
        'class'       => '',
        'css'         => '',
        'placeholder' => __( 'Enter my message', 'woocommerce' ),
        'desc_tip'    => __( 'This is the message that appears when..', 'woocommerce' ),
    );
    
    $settings[] = array(
        'type' => 'sectionend',
        'id'   => 'product_inventory_custom_options',
    );

    return $settings;
}
add_filter( 'woocommerce_inventory_settings', 'filter_woocommerce_inventory_settings', 10, 1 );

要在代码的其他地方或网站上获取值,请使用 get_option( string $option, mixed $default = false ) - 根据选项名称检索选项值。

// Get message from field
$get_option = get_option( 'woocommerce_my_message' );