本文介绍了WooCommerce:从产品变体中获取自定义字段并将其显示为变体价格的后缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从产品变体的自定义数字字段中获取值,并将其显示为变体价格的后缀以及自定义文本.
I'm trying to get a value from a custom numbers field on product variations, and show it as a suffix to variation prices along with custom text.
我在工作
这就是我所拥有的:
// 1. Add custom field input @ Product Data > Variations > Single Variation
add_action( 'woocommerce_variation_options_pricing', 'Add_bulk_price_to_variations', 10, 3 );
function Add_bulk_price_to_variations( $loop, $variation_data, $variation ) {
woocommerce_wp_text_input( array(
'id' => 'bulk_price[' . $loop . ']',
'desc_tip' => 'true',
'description' => __( 'Enter the Bulk price here.', 'woocommerce' ),
'label' => __( 'Custom Field', 'woocommerce' ),
'value' => get_post_meta( $variation->ID, 'bulk_price', true )
));
}
// 2. Save custom field on product variation save
add_action( 'woocommerce_save_product_variation', 'Save_bulk_price_variations', 10, 2 );
function Save_bulk_price_variations( $variation_id, $i ) {
$bulk_price = $_POST['bulk_price'][$i];
if ( isset( $bulk_price ) ) {
update_post_meta( $variation_id, 'bulk_price', esc_attr( $bulk_price ) );
}
}
// 3. Store custom field value into variation data
add_filter( 'woocommerce_available_variation', 'Add_bulk_price_variation_data' );
function Add_bulk_price_variation_data( $variations ) {
$variations['bulk_price'] = '<div class="woocommerce_bulk_price">Custom Field: <span>' . get_post_meta( $variations[ 'variation_id' ], 'bulk_price', true ) . '</span></div>';
return $variations;
}
// 4. Show the bulk price on product variations
function variation_price_custom_suffix( $variation_data, $product, $variation ) {
// Get childIDs in an array
$children_ids = $variations->get_children();
foreach ( $children_ids as $child_id ) {
$value = get_post_meta( $child_id, 'bulk_price', true );
// True
if ( $value ) {
$variation_data['price_html'] .= ' <span class="price-suffix">' . $value . __("custom text", "woocommerce") . '</span>';
return $variation_data;
}
add_filter('woocommerce_available_variation', 'variation_price_custom_suffix', 10, 3 );
推荐答案
您使用相同的钩子 2x,这应该足够了(不再需要步骤 4)
You use the same hook 2x, this should suffice (where step 4 is no longer needed)
不需要使用 foreach
循环来获取子 ID
The use of a foreach
loop to get the child ID's is not necessary
// 3 & 4. Store custom field value into variation data + show the bulk price on product variations
function add_bulk_price_variation_data( $variation_data, $product, $variation ) {
$bulk_price = get_post_meta( $variation_data[ 'variation_id' ], 'bulk_price', true);
if ( $bulk_price ) {
$variation_data['price_html'] .= ' <span class="price-suffix">' . __( $bulk_price , "woocommerce") . '</span>';
}
return $variation_data;
}
add_filter( 'woocommerce_available_variation', 'add_bulk_price_variation_data', 10, 3 );
这篇关于WooCommerce:从产品变体中获取自定义字段并将其显示为变体价格的后缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!