我在为Woocommerce上的变体设置自定义字段时遇到问题。我跟踪了这个very helpful tutorial 一切都很顺利,只是我的字段值没有保存在Woocommerce 2.4.6中。基本上,我输入一个值,更新帖子,然后值消失。
根据那本原始教程的评论,我似乎并不孤单。然而,所有发布的资源,包括separate post on this same topic 在StackExchange上,以及我在网上发现的其他一些网站实际上并不适合我。
下面是我的函数文件摘录。如您所见,我只是想设置一个自定义文本字段作为概念证明,称为“电压”使用此函数,字段确实会显示在后端,但分配给它的值在产品发布后不会保持不变。
最终会有几个额外的字段,我需要能够根据选择在前端更新这些字段(如SKU)。但现在,我甚至无法保存这些值。有人能提供帮助吗?:-/
<?php
/* Add Custom Fields to Variation Products */
//Display Fields
add_action( \'woocommerce_variation_options\', \'variable_fields\', 10, 3 );
//JS to add fields for new variations
add_action( \'woocommerce_product_after_variable_attributes_js\', \'variable_fields_js\' );
//Save variation fields
add_action( \'woocommerce_save_product_variation\', \'save_variable_fields\', 10, 1 );
add_action( \'woocommerce_process_product_meta_variable-subscription\' , \'save_variable_fields\' , 10 , 1 ) ;
// -------------------------------------------------------------------------------------
// Create new fields for variations
// ------------------------------------------------------------------------------------
function variable_fields( $loop, $variation_data ) {
?>
<tr>
<td>
<?php
// Text
woocommerce_wp_text_input(
array(
\'id\' => \'_voltage[\'.$loop.\']\',
\'label\' => __( \'Voltage\', \'woocommerce\' ),
\'placeholder\' => \'\',
\'description\' => __( \'Enter the voltage here.\', \'woocommerce\' ),
\'value\' => get_post_meta($variation->ID, \'_voltage\', true)
)
);
?>
</td>
</tr>
<?php
}
// -------------------------------------------------------------------------------------
// Create new fields for new variations, yes again.
// ------------------------------------------------------------------------------------
function variable_fields_js() {
?>
<tr>
<td>
<?php
// text
woocommerce_wp_text_input(
array(
\'id\' => \'_voltage[ + loop + ]\',
\'label\' => __( \'Voltage\', \'woocommerce\' ),
\'placeholder\' => \'\',
\'description\' => __( \'Enter the voltage here.\', \'woocommerce\' ),
\'value\' => get_post_meta($variation->ID, \'_voltage\', true)
)
);
?>
</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
$_voltage = $_POST[\'_voltage\'];
for ( $i = 0; $i < sizeof( $variable_sku ); $i++ ) :
$variation_id = (int) $variable_post_id[$i];
if ( isset( $_voltage[$i] ) ) {
update_post_meta( $variation_id, \'_voltage\', stripslashes( $_voltage[$i] ) );
}
endfor;
endif;
}