我正在尝试在我的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';
}
?>
当我检查后端时,看起来它正在将所有后置元素拉入每个变体中,如下所示:
但是,如果我使用如下所示的实际变体ID,那么它适用于该变体:
echo get_post_meta( 134, '_my_custom_field', true) . ' - Test Variation #134';
答案 0 :(得分:2)
@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;
?>
答案 1 :(得分:0)
您在foreach循环中应该可以通过以下方式访问它:
$variation->variation_id or $variation['variation_id']
这看起来像是:
foreach ( $variations as $variation ) {
$variation_id = $variation->variation_id );
}
您也可以使用 get_the_ID()功能