WooCommerce添加到购物车并覆盖价格

问题描述 投票:1回答:1

在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一直在拉我的头发任何建议,不胜感激。非常感谢

wordpress woocommerce cart
1个回答
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' );

尝试此代码

© www.soinside.com 2019 - 2024. All rights reserved.