【发布时间】:2014-04-20 15:33:14
【问题描述】:
我正在尝试找到在前端获取自定义字段变化数据的解决方案。我不确定如何在更改变体产品列表框时获取变体 ID。例如可变产品作为颜色包含红色、蓝色、绿色。我为所有颜色组合添加了自定义字段。
这是我尝试过的代码 (source)
add_action('woocommerce_product_after_variable_attributes', 'variable_fields', 10, 2);
//JS to add fields for new variations
add_action('woocommerce_product_after_variable_attributes_js', 'variable_fields_js');
//Save variation fields
add_action('woocommerce_process_product_meta_variable', 'save_variable_fields', 10, 1);
/**
* Create new fields for variations
*
*/
function variable_fields($loop, $variation_data) {
?>
<tr>
<td>
<?php
// Select
woocommerce_wp_select(
array(
'id' => '_select[' . $loop . ']',
'label' => __('My Select Field', 'woocommerce'),
'description' => __('Choose a value.', 'woocommerce'),
'value' => $variation_data['_select'][0],
'options' => array(
'one' => __('Option 1', 'woocommerce'),
'two' => __('Option 2', 'woocommerce'),
'three' => __('Option 3', 'woocommerce')
)
)
);
?>
</td>
</tr>
<?php
}
/**
* Create new fields for new variations
*
*/
function variable_fields_js() {
?>
<tr>
<td>
<?php
// Select
woocommerce_wp_select(
array(
'id' => '_select[ + loop + ]',
'label' => __('My Select Field', 'woocommerce'),
'description' => __('Choose a value.', 'woocommerce'),
'value' => $variation_data['_select'][0],
'options' => array(
'one' => __('Option 1', 'woocommerce'),
'two' => __('Option 2', 'woocommerce'),
'three' => __('Option 3', 'woocommerce')
)
)
);
?>
</td>
</tr>
<?php
}
/**
* Save new fields for variations
*
*/
function save_variable_fields($post_id) {
if (isset($_POST['variable_sku'])) :
$variable_sku = $_POST['variable_sku'];
$variable_post_id = $_POST['variable_post_id'];
// Text Field
$_select = $_POST['_select'];
for ($i = 0; $i < sizeof($variable_sku); $i++) :
$variation_id = (int) $variable_post_id[$i];
if (isset($_select[$i])) {
update_post_meta($variation_id, '_select', stripslashes($_select[$i]));
}
endfor;
// Checkbox
endif;
}
这一切都正确保存,但在前端我无法获得相应变化的值,但我仍在寻找解决方案。 就像在前端一样,如果你改变它同时改变价格的变化。我想在变化价格之上显示另一个信息。在woocommerce中可以做到这一点吗? 这是屏幕截图。
后端可变产品
前端的预期输出
如何在更改列表框时显示自定义字段数据?
【问题讨论】:
标签: php woocommerce wordpress