Woocommerce: Добавление кастомного поля в вариативный продукт


if(!function_exists('wc_custom_product_data_fields')){

    // Display Fields
    add_action( 'woocommerce_product_options_general_product_data', 'woo_add_custom_general_fields' );

    function woo_add_custom_general_fields() {
        global $woocommerce, $post;
        echo '<div class="options_group">';

        woocommerce_wp_text_input(
            array(
                'id'          => '_custom_field',
                'label'       => __( '_custom_field', 'woocommerce' ),
                'placeholder' => __( '', 'woocommerce' ),
                'class'       => 'wc_input_price short',
                'desc_tip'    => 'true',
                'description' => __( '_custom_field', 'woocommerce' ),
                //'type'              => 'number',
                'required' => 'required',
                'custom_attributes' => array()
            )
        );
        echo '</div>';
    }

    // Save Fields
    add_action( 'woocommerce_process_product_meta', 'woo_add_custom_general_fields_save' );
    function woo_add_custom_general_fields_save( $post_id ){
        $woocommerce_text_lpreis = $_POST['_custom_field']; //number_format($_POST['_custom_field'],2,'.','');
        if( !empty( $woocommerce_text_lpreis ) ){
            update_post_meta($post_id, '_custom_field', esc_attr( $woocommerce_text_lpreis) );
        }
    }

}



add_action( 'woocommerce_product_after_variable_attributes', 'add_to_variations_metabox', 10, 3 );
add_action( 'woocommerce_save_product_variation', 'save_product_variation', 20, 2 );



function add_to_variations_metabox( $loop, $variation_data, $variation ){

    $custom = get_post_meta( $variation->ID, '_custom_field', true ); ?>

    <div class="variable_custom_field">
        <p class="form-row form-row-first">
            <label>_custom_field</label>
            <input type="text" name="variation_custom_data[<?php echo $loop; ?>]" value="<?php echo esc_attr( $custom ); ?>" />
        </p>
    </div>

    <?php

}


function save_product_variation( $variation_id, $i ){

    // save custom data
    if ( isset( $_POST['variation_custom_data'][$i] ) ) {
        // sanitize data in way that makes sense for your data type
        $custom_data = ( trim( $_POST['variation_custom_data'][$i]  ) === '' ) ? '' : $_POST['variation_custom_data'][$i];
        update_post_meta( $variation_id, '_custom_field', $custom_data );
    }

}