【问题标题】:WooCommerce add to cart and override priceWooCommerce 添加到购物车并覆盖价格
【发布时间】:2026-01-06 23:25:02
【问题描述】:

在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 域),custom_price 应设置为 12,但它一直输入 10 的假值 一直在拉我的头发 非常感谢任何建议。 非常感谢

【问题讨论】:

  • *.com/a/6987496/1117368 - 检查一下
  • 您好 还是不行。我已经尝试过 strcmp 和 strpos 两者都是区分大小写的,并且我将所有内容都设为小写但仍然不喜欢它
  • esc_attr( $_GET['domain_name_meta'] ) 的输出是什么?
  • 您好,输出是一个域名,例如:anydomain.com 或其他 TLDc。目前我正在使用 anydomain.com 对其进行测试,因此从 substr 中选择的最后 4 个是 .com。我已经更正了上面代码中的一个错误(我在这里打错了)正确的代码在下面。它在其他任何地方都有效。例如在屏幕上显示 custom_price。它只是在出错的数据库中设置自定义价格
  • 我刚刚将上面的代码调整为当前正在使用的部分,错误已更正但仍然相同

标签: wordpress woocommerce cart hook-woocommerce price


【解决方案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' );

试试这个代码

【讨论】:

  • 嗨 还是一样的结果 :( 即使是 .com 仍然添加 10 而不是 12 但是很多人看它