将自定义字段添加到发货选项卡中的 WooCommerce 产品设置页面

Add custom fields to WooComerce product setting pages in the shipping tab

是否可以在后端的 WooCommerce 产品页面发货选项卡设置中添加一些额外的字段,因为我需要添加 12 个自定义字段之类的东西。

我试图找到一些相关的钩子,但没有成功。我找到的唯一方法是通过属性,但这不是一个方便的解决方案……

如何将自定义字段添加到发货选项卡中的 WooComerce 产品设置页面?

谢谢。

这是可能的,你会得到这个(这里我已经设置为自定义文本字段):

代码如下:

// Add custom fields to product shipping tab
add_action( 'woocommerce_product_options_shipping', 'add_custom_shipping_option_to_products');
function add_custom_shipping_option_to_products(){
    global $post, $product;


    echo '</div><div class="options_group">'; // New option group

    woocommerce_wp_text_input( array(
        'id'          => '_custom_text_field1',
        'label'       => __( 'My Text Field one', 'woocommerce' ),
        'placeholder' => 'something',
        'desc_tip'    => 'true',
        'description' => __( 'Enter the custom value here.', 'woocommerce' ),
        'value'       => get_post_meta( $post->ID, '_custom_meta_field1', true ),
    ) );

    woocommerce_wp_text_input( array(
        'id'          => '_custom_text_field2',
        'label'       => __( 'My Text Field two', 'woocommerce' ),
        'placeholder' => 'something',
        'desc_tip'    => 'true',
        'description' => __( 'Enter the custom value here.', 'woocommerce' ),
        'value'       => get_post_meta( $post->ID, '_custom_meta_field2', true ),
    ) );
}

// Save the custom fields values as meta data
add_action( 'woocommerce_process_product_meta', 'save_custom_shipping_option_to_products' );
function save_custom_shipping_option_to_products( $post_id ){

    $custom_text_field1 = $_POST['_custom_text_field1'];
    if( isset( $custom_text_field1 ) )
        update_post_meta( $post_id, '_custom_meta_field1', esc_attr( $custom_text_field1 ) );

    $custom_text_field2 = $_POST['_custom_text_field2'];
    if( isset( $custom_text_field2 ) )
        update_post_meta( $post_id, '_custom_meta_field2', esc_attr( $custom_text_field2 ) );
}

代码进入您的活动子主题(或主题)的 function.php 文件或任何插件文件。

此代码已在 WooCommerce 3+ 上测试并有效