Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
363 views
in Technique[技术] by (71.8m points)

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

Is it possible to do add some extra fields in WooCommerce products pages shipping tab settings in backend, as I need to add something like 12 custom fields.

I have tried to find some related hooks without success. The only way that I have found was over attributes, but it was not a convenient solution…

How can I add custom fields to WooComerce product setting pages in the shipping tab?

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is possible and you will get this (here I have set to custom text fields):

enter image description here

Here is the code:

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

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested on WooCommerce 3+ and works


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...