2014-01-14 56 views
3

我想在我的Woocommerce後端創建一些額外的功能,我添加一個自定義字段到Woocommerce後端的變體部分。然而,我不能爲我的生活弄清楚如何獲得當前的變化id,所以我可以得到後期元。如何獲取Woocommerce當前的變體ID?

這裏是我一直在努力什麼:

<?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'; 

       } 

    ?> 

當我檢查它看起來是拉動所有的職位元到這樣每個變體後端:

enter image description here

但是,如果我使用如下所示的實際變化ID,那麼它適用於該變體:

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

你可能有更好的運氣在[WordPress的答案](http://wordpress.stackexchange.com/)(WordPress開發人員和管理員的StackExchange站點)獲得答案。 – RobertB

+0

謝謝RobertB,我接受了你的建議。不幸的是,我還沒有得到答案,但我會繼續檢查,我認爲這對於正確的思想來說是一個非常容易的問題。再次感謝。 – Derek

回答

2

@Derek,

您的模板中的哪個位置試圖讓自定義字段數據顯示?在您的foreach循環

<?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; 
?> 
0

你,你應該能夠通過訪問它:

如果它是產品的循環中,你可以做到這一點

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

這將是這樣的:

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

您可能還可以使用get_the_ID()函數