简体   繁体   中英

Unable to get woocoommerce product variation id

I am trying to update a specific field for all variations in a product but unfortunately I am unable to get variation ids to go further.

Basically what I am doing is, I am trying to get each variation's stock value and if the stock value is less than zero, then I am updated a particular field with certain values (as mentioned in my code below).

I have tested this by manually inputting any custom post / variation id and is working fine, updates that particular variation id based on its stock value. All I am stuck here is I am unable to fetch the variation id by itself.

Below is the code that I am using:

global $post, $woocommerce;
$post_id = $variation->ID;

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

if ($stock < 1) {
    update_post_meta( $post_id, 'cuzd-prod-general-v', '20,25' );   
} else {
    update_post_meta( $post_id, 'cuzd-prod-general-v', '1,5' );
}

I don't know where I am wrong to get the variation ids for this.

I was able to solve this by using below code changes:

// Values to be updated
    $in_stock   = '1,5';
    $out_of_stock   = '20,30';

// 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;


    // Get specific data from the certain custom fields using get_post_meta( $post_id, $key, $single );
    $stock = get_post_meta( $variation_data['variation_post_id'], '_stock', true ); 


    if ($stock < 1) {
        update_post_meta( $variation_data['variation_post_id'], 'cuzd-prod-general-v', $out_of_stock ); 
        } else {
            update_post_meta( $variation_data['variation_post_id'], 'cuzd-prod-general-v', $in_stock );
            }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM