WP SITES

3086 Coded Tutorials & 290 Plugins

How To Add 1 Custom Field To Both Simple & Variable Products

Add the PHP code to the end of your child themes functions file to add one custom field that works on both simple and variable products in WooCommerce.

add_action( 'woocommerce_product_options_general_product_data', 'wpsitesdoetnet_add_custom_field_to_general_tab_v1' );
function wpsitesdotnet_add_custom_field_to_general_tab_v1() {

    global $woocommerce, $post;

    echo '<div class="options_group">';
    
    woocommerce_wp_text_input( array(
        'id'            => '_custom_field_id',
        'label'         => __( 'Custom Field', 'woocommerce' ),
        'placeholder'   => 'Enter custom field value',
        'description'   => __( 'This is a custom field for variable products.', 'woocommerce' ),
        'desc_tip'      => 'true',
    ) );
    
    echo '</div>';
}

add_action( 'woocommerce_process_product_meta', 'save_custom_field_v1' );
function save_custom_field_v1( $post_id ) {

    $custom_field_value = isset( $_POST['_custom_field_id'] ) ? sanitize_text_field( $_POST['_custom_field_id'] ) : '';

    update_post_meta( $post_id, '_custom_field_id', $custom_field_value );

}

This code only uses 1 custom field for 2 product types, simple and variable products and display the general tab when using variable products.

The only problem is, it only adds a 1 custom field the general tab for variable products when you might need to add a field foreach variation.

Leave a Reply

New Plugins