提问者:小点点

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


在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语句是真的(如果我添加了一个.com域),那么定制价格应该设置为12,但它不断输入错误的值10。对此,我非常感谢任何建议。非常感谢


共1个答案

匿名用户

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' );

试试这个代码