Derek
Derek

Reputation: 5037

How to get Woocommerce Current Variation ID?

I am trying to create some additional functionality on my Woocommerce backend where I add a custom field to the variations section of backend of Woocommerce. However I cannot for the life of me figure out how to get the current variation id so I can get the post meta.

here is what I have been working with:

<?php

        // Get variations
        $args = array(
                     'post_type'     => 'product_variation',
                     'post_status'   => array( 'private', 'publish' ),
                     'numberposts'   => -1,
                     'orderby'       => 'menu_order',
                     'order'         => 'asc',
                     'post_parent'   => $post->ID
                 );
                 $variations = get_posts( $args ); 

        foreach ( $variations as $variation ) {

                     $variation_id           = absint( $variation->ID );$variable_id = $this['variation_id'];
                     $variation_post_status  = esc_attr( $variation->post_status );
                     $variation_data         = get_post_meta( $variation_id );
                     $variation_data['variation_post_id'] = $variation_id;
                    echo get_post_meta( $variation_data['variation_post_id'], '_my_custom_field', true) . ' - TEST';

                 }

     ?>

When I check the backend it looks like it is pulling all the post meta into each variation like this:

enter image description here

However if I use the actual variation id like the below then it works for that variation:

echo get_post_meta( 134, '_my_custom_field', true) . ' - Test Variation #134';

Upvotes: 3

Views: 19861

Answers (2)

David
David

Reputation: 181

You in your foreach loop you should be able to access it via:

$variation->variation_id or $variation['variation_id']

This would look like:

foreach ( $variations as $variation ) {
  $variation_id       = $variation->variation_id );
}

You may also be able to use the get_the_ID() function

Upvotes: 0

gui_ermo
gui_ermo

Reputation: 41

@Derek,

Where in your template are you trying to get the custom field data to display?

If it is within the product loop, you can do this:

<?php
    // Get the post IDs of all the product variations
    $variation_ids = $product->children;

    // Each product variation id
    foreach( $variation_ids as $var_id ) :

        // Get all of the custom field data in an array
        $all_cfs = get_post_custom($var_id); 

        // Show all of the custom fields    
        var_dump($all_cfs); 

        // Get specific data from the certain custom fields using get_post_meta( $post_id, $key, $single );
        $test = get_post_meta( $var_id, '_text_field', true );

    endforeach;
?>

Upvotes: 2

Related Questions