[英]Custom Field in WooCommerce variations
我試圖找到在前端獲取自定義字段變體數據的解決方案。 我不確定如何在更改變體產品的列表框時獲取變體ID。 例如,作為顏色的可變產品包含紅色,藍色,綠色。 我為所有顏色組合添加了自定義字段。
這是我嘗試過的代碼( 來源 )
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中做。 這是截圖。
后端變量產品
前端的預期輸出
如何在更改列表框時顯示自定義字段數據?
brasofilo,
我在這里寫了一個關於這個問題的教程/示例:
我有同樣的問題,並想出辦法來做到這一點。 這並不像人們想象的那么簡單。 它需要一點點的一切,但最終的訣竅在於使用jQuery來顯示和隱藏內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.