首页 > 解决方案 > 如何将自定义字段添加到 WooCommerce 设置中的“产品库存”选项卡?

问题描述

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

见附图:

存货


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

标签: phpwordpresswoocommercehook-woocommercecustom-fields

解决方案


woocommerce_inventory_settings可以class-wc-settings-products.php在线找到该钩子(在 WooCommerce 4.4.1 中)81

所以你可以使用

// 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' );

推荐阅读