[英]How to get Woocommerce Current Variation ID?
我正在嘗試在我的Woocommerce后端創建一些額外的功能,我在Woocommerce的后端的變體部分添加了一個自定義字段。 但是我不能為我的生活弄清楚如何獲得當前的變異id所以我可以獲得post meta。
這是我一直在做的事情:
<?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';
}
?>
當我檢查后端時,看起來它將所有post meta拉入每個變體中,如下所示:
但是,如果我使用下面的實際變體ID,那么它適用於該變體:
echo get_post_meta( 134, '_my_custom_field', true) . ' - Test Variation #134';
@Derek,
您在模板中的哪個位置嘗試顯示自定義字段數據?
如果它在產品循環中,您可以這樣做:
<?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;
?>
您在foreach循環中應該可以通過以下方式訪問它:
$variation->variation_id or $variation['variation_id']
這看起來像:
foreach ( $variations as $variation ) {
$variation_id = $variation->variation_id );
}
您也可以使用get_the_ID()函數
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.