wordpress 无法获取WooCoommerce产品变体ID

ycl3bljg  于 2022-11-22  发布在  WordPress
关注(0)|答案(1)|浏览(182)

我试图更新产品中所有变体的特定字段,但不幸的是,我无法获得变体ID以更进一步。
基本上,我正在做的是,我试图得到每个变量的股票值,如果股票值小于零,那么我用特定的值更新特定的字段(如下面的代码所述)。
我已经通过手动输入任何自定义帖子/变体ID进行了测试,并且工作正常,根据其股票价值更新特定的变体ID。我在这里遇到的所有问题是我无法自行获取变体ID。
下面是我正在使用的代码:

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' );
}

我不知道我哪里错了,得到了这个的变异ID。

bttbmeg0

bttbmeg01#

我能够通过使用以下代码更改来解决此问题:

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

相关问题