我要在产品页面上动态更新价格。
我有一个自定义价格功能,可为每个自定义用户输入字段(宽度高度)生成价格。
自定义价格在购物车和结帐时有效。
基于输入范围的价格:
function hmrc_add_custom_price_field_item_data( $cart_item_data, $product_id, $variation_id, $quantity ) {
if( ! empty( $_POST['hmrc-height-title-field'] ) ) {
$height = $_POST['hmrc-height-title-field'];
$width = $_POST['hmrc-width-title-field'];
$totalcalc = $height . 'mm x ' . $width . 'mm';
$cart_item_data['title_field'] = $totalcalc;
$product = wc_get_product( $product_id );
$price = $product->get_price();
if( $width <= 800 && $height <= 800) {
$cart_item_data['total_price'] = 64.99;
} elseif( $width <= 800 && $height >= 800 && $height <= 900) {
$cart_item_data['total_price'] = 66.99;
} elseif( $width <= 800 && $height >= 900 && $height <= 1000) {
$cart_item_data['total_price'] = 67.99;
} elseif( $width <= 800 && $height >= 1000 && $height <= 1200) {
$cart_item_data['total_price'] = 69.99;
} elseif( $width <= 800 && $height >= 1200 && $height <= 1400) {
$cart_item_data['total_price'] = 74.99;
} elseif( $width <= 800 && $height >= 1400 && $height <= 1600)
// … and so on
}
return $cart_item_data;
}
add_filter( 'woocommerce_add_cart_item_data', 'hmrc_add_custom_price_field_item_data', 10, 4 );
它适用于购物车和结帐:
function hmrc_before_calculate_totals( $cart_obj ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
return;
}
// Iterate through each cart item
foreach( $cart_obj->get_cart() as $key=>$value ) {
if( isset( $value['total_price'] ) ) {
$price = $value['total_price'];
$value['data']->set_price( ( $price ) );
}
}
}
add_action( 'woocommerce_before_calculate_totals', 'hmrc_before_calculate_totals', 10, 1 );
function hmrc_cart_item_name( $name, $cart_item, $cart_item_key ) {
if( isset( $cart_item['title_field'] ) ) {
$name .= sprintf(
'<p>%s</p>',
esc_html( $cart_item['title_field'] )
);
}
return $name;
}
add_filter( 'woocommerce_cart_item_name', 'hmrc_cart_item_name', 10, 3 );
希望任何人都可以帮助我。