How to add a Custom Fields in Woocommerce 3.1

2019-09-18 07:15发布

问题:

i've tried many methods to make a custom fields in woocommerce 3.1 but this code didnt work for me.

can any one help me to figure out how to add a custom fields like this on the link below http://www.remicorson.com/mastering-woocommerce-products-custom-fields/

Best regards

回答1:

Add Custom fields in Product General tab used woocommerce_product_options_general_product_data action hook

add_action( 'woocommerce_product_options_general_product_data', 'woo_add_custom_general_fields' );

function woo_add_custom_general_fields() {

  global $woocommerce, $post;

    woocommerce_wp_text_input( 
        array( 
            'id'          => '_text_field', 
            'label'       => __( 'My Text Field', 'woocommerce' ), 
            'placeholder' => 'http://',
            'desc_tip'    => 'true',
            'description' => __( 'Enter the custom value here.', 'woocommerce' ) 
        )
    );

}

Now For Saving this fields to data based using woocommerce_process_product_meta

add_action( 'woocommerce_process_product_meta', 'woo_add_custom_general_fields_save' );
function woo_add_custom_general_fields_save( $post_id ){
    $woocommerce_text_field = $_POST['_text_field'];
    if( !empty( $woocommerce_text_field ) )
        update_post_meta( $post_id, '_text_field', esc_attr( $woocommerce_text_field ) );

}

i hop now you understand. it working with WooCommerce 3.1