【发布时间】:2021-06-11 04:52:43
【问题描述】:
这就是我为产品变体添加管理自定义字段的方法:
add_action( 'woocommerce_variation_options_pricing', 'add_custom_field_to_variations', 10, 3 );
function add_custom_field_to_variations( $loop, $variation_data, $variation ) {
woocommerce_wp_text_input( array(
'id' => 'custom_field[' . $loop . ']',
'class' => 'short',
'label' => __( 'Custom Field', 'woocommerce' ),
'value' => get_post_meta( $variation->ID, 'custom_field', true )
) );
}
保存产品变体保存的自定义字段:
add_action( 'woocommerce_save_product_variation', 'save_custom_field_variations', 10, 2 );
function save_custom_field_variations( $variation_id, $i ) {
$custom_field = $_POST['custom_field'][$i];
if ( isset( $custom_field ) ) update_post_meta( $variation_id, 'custom_field', esc_attr( $custom_field ) );
}
将自定义字段值存储到变体数据中
add_filter( 'woocommerce_available_variation', 'add_custom_field_variation_data' );
function add_custom_field_variation_data( $variations ) {
$variations ['custom_field'] = '<div class="woocommerce_custom_field">Custom Field: <span>' . get_post_meta( $variations[ 'variation_id' ], 'custom_field', true ) . '</span></div>';
return $variations;
}
数值在单品页面保存显示,但下面的函数没有返回数值
尝试在函数中检索自定义字段的值:
add_filter('woocommerce_variation_prices_price', 'get_custom_variable_price' )
function get_custom_variable_price() {
global $post;
$custom_value = get_post_meta( $variations[ 'variation_id' ], 'custom_field', true );
$custom_value = (float)$custom_value;
return $custom_value;
}
我只需要获取值(浮点数):
【问题讨论】:
-
你在哪里使用你的最后一个函数?...请添加更多上下文,因为您的问题实际上还不清楚...
-
我在“woocommerce_variation_prices_price”上使用最后一个函数。目的是让自定义值乘以变体产品价格
-
我已经编辑了你的问题,并回答了。请对以下答案提供一些反馈。
标签: php wordpress woocommerce custom-fields product-variations