How to get Woocommerce Variation ID?

天大地大妈咪最大 提交于 2019-12-01 21:06:41
Sunil Dora

Try this one:

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

foreach ( $variations as $variation ) {

    // get variation ID
    $variation_ID = $variation->ID;

    // get variations meta
    $product_variation = new WC_Product_Variation( $variation_ID );

    // get variation featured image
    $variation_image = $product_variation->get_image();

    // get variation price
    $variation_price = $product_variation->get_price_html();

    get_post_meta( $variation_ID , '_text_field_date_expire', true );

}

Hope this will helps you. For more information:

In WooCommerce 3+, it's $variation->get_id() from $variation function argument, which is an instance of the WC_Product_Variation.

The method get_id() is inherited from WC_Data class.

So in your code it should be instead:

'id' => '_text_field_date_expire[' . $variation->get_id() . ']',

Since WooCommerce 3, All WC_Product properties can't be accessed directly. Instead, you need to use the available methods.


Also in your hooked function save_variation_settings_fields() you are declaring 2 arguments, so there is one missing. It should be:

//Save New Fields for Variation
function save_variation_settings_fields( $variation_id, $i ) {
    // Text Field
    $text_field = $_POST['_text_field_date_expire'][ $variation_id ];
    if( ! empty( $text_field ) ) {
        update_post_meta( $variation_id, '_text_field_date_expire', esc_attr( $text_field ) );
    }
}

See the source code for woocommerce_save_product_variation action hook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!