在WordPress v5.4中使用最新版本的woocommerce V4.01 我已经在互联网上拖拉了很长时间,但似乎无法找到有效的答案。
通过URL链接将商品添加到购物车时,我需要覆盖购物车价格并输入新价格。
这是我的功能页面上的内容
function add_custom_price( $cart_object ) {
$target_product_id = 6048;
if ( !isset( $_GET[ 'add-to-cart' ] ) ) //** this is the product id sent through
$add_to_cart = esc_attr( $_GET[ 'add-to-cart' ] );
if ( $add_to_cart = $target_product_id ) {
$domain_name_meta = esc_attr( $_GET[ 'domain_name_meta' ] ); //**the domain with extension sent through
$reg = strtolower( substr( $domain_name_meta, -4 ) );
$ext = ".com";
if ( strcmp( $reg, $ext ) !== 0 ) {
$custom_price = 10;
} else {
$custom_price = 12;
}
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
if ( $cart_item[ 'product_id' ] == $target_product_id ) {
$cart_item[ 'data' ]->price = $custom_price;
$found = true;
$cart_item[ 'data' ]->set_price( $custom_price );
}
}
}
}
add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );
以上方法有效,但不能正确执行,并且存在以下问题:
我已经检查过strpos
语句,它工作正常。因此,如果strpos
语句为true(这是我添加.com域的情况),则custom_price应该设置为12,但它始终输入错误的值10
一直在拉我的头发
任何建议,不胜感激。
非常感谢
答案 0 :(得分:0)
function add_custom_price( $cart_object ) {
$target_product_id = 6048;
if ( !empty( $_GET[ 'add-to-cart' ] ) ) //** this is the product id sent through
$add_to_cart = esc_attr( $_GET[ 'add-to-cart' ] );
if ( $add_to_cart = $target_product_id ) {
$domain_name_meta = esc_attr( $_GET[ 'domain_name_meta' ] ); //**the domain with extension sent through
$custom_price = 10;
if ( strtolower( substr( $domain_name_meta, -4 ) ) === ".com" ) {
$custom_price = 12;
}
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
if ( $cart_item[ 'product_id' ] == $target_product_id ) {
$cart_item[ 'data' ]->price = $custom_price;
$found = true;
$cart_item[ 'data' ]->set_price( $custom_price );
}
}
}
}
add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );
尝试此代码