Search code examples
phpwordpresswoocommerceproduct-variations

Woocommerce 3.1 product variation meta data


I have currently added metadata to a product variation woocommerce_product_after_variable_attributes and woocommerce_save_product_variation Guide here.

function custom_woocommerce_product_after_variable_attributes($loop, $variation_data, $variation)
{
    woocommerce_wp_select([
        'id' => 'field_1['.absint($variation->ID).']',
        'label' => 'Field 1 ',
        'value' => get_post_meta(absint($variation->ID), 'field_1', true),
        'options' => [
            '1' => '1',
            '2' => '2',
            '3' => '3',
        ],
    ]);
}
add_action('woocommerce_product_after_variable_attributes', 'custom_woocommerce_product_after_variable_attributes', 10, 3);

function custom_woocommerce_save_product_variation($post_id)
{
    $field1 = $_POST['field_1'][$post_id];
    if (! empty($field1)) {
        update_post_meta(absint($post_id), 'field_1', esc_html($field1));
    }
}
add_action('woocommerce_save_product_variation', 'custom_woocommerce_save_product_variation', 10, 2);

Then in the js hooked into single_variation_wrap when the variation was changed. This was working fine in 3.0.5 but since updating to 3.1.1 in the js i am no longer getting the custom meta_data for variations.

$('.single_variation_wrap').on('show_variation', function(event, variation) {
    console.log(variation.meta_data);
});

The meta_data information no longer exists.

How can this be fixed?


Solution

  • I was able to fix this by adding a filter.

    function custom_woocommerce_available_variation($variations, $product, $variation)
    {
        $metadata = $variation->get_meta_data();
        if (!empty($metadata)) {
            $variations = array_merge($variations, [
                'meta_data' => $metadata,
            ]);
        }
    
        return $variations;
    }
    add_filter('woocommerce_available_variation', 'custom_woocommerce_available_variation', 10, 3);