【问题标题】:Update woocommerce price of a product based on php基于php更新产品的woocommerce价格
【发布时间】:2021-08-01 09:52:11
【问题描述】:

我在 php 中有一个针对单个产品的自定义添加到购物车按钮:

Final total<br>
            $<?php echo $row['purchase-price'] ?>.00<br><br>
            <button onclick="window.location.href='https://yourdomain.com/checkout/?add-to-cart=362166';">Add to cart</button>

点击按钮后,返回“对不起,该产品无法购买”。错误。我没有设置产品价格,因为&lt;?php echo $row['purchase-price'] ?&gt; 中的金额总是在变化。如何将php中设置的金额传递给产品的最终价格?

【问题讨论】:

  • 在您的 URL 后面设置数量参数,例如 checkout/?add-to-cart=362166&amp;quantity=3。如果您想从 URL 传递价格,那么每个人都可以在发送添加到购物车请求时设置价格。这个想法不是不安全的方式,而是设置 addtocart 钩子并在添加到购物车之前解析要计算的参数。

标签: php mysql wordpress woocommerce


【解决方案1】:
  1. 首先,您将代码限制在单个产品和存档页面上:
add_filter( 'woocommerce_product_get_price', 'double_price', 10, 2 );

function double_price( $price, $product ){
    if( is_shop() || is_product_category() || is_product_tag() || is_product() ) {
        global $wpdb;
        //your query to get price from custom db
        //FOR GET PRODUCT ID $product->get_id();
        $price = $row['purchase-price'];
    }
    return $price;
}
  1. 然后对于购物车和结帐页面,您将通过以下方式更改购物车商品价格:
add_filter( 'woocommerce_add_cart_item', 'set_custom_cart_item_prices', 20, 2 );
function set_custom_cart_item_prices( $cart_data, $cart_item_key ) {
    global $wpdb;
    //your query to get price from custom db
    $new_price = $row['purchase-price'];

    //FOR GET PRODUCT ID $cart_item['data']->get_id();

    // Set and register the new calculated price
    $cart_data['data']->set_price( $new_price );
    $cart_data['new_price'] = $new_price;

    return $cart_data;
}

add_filter( 'woocommerce_get_cart_item_from_session', 'set_custom_cart_item_prices_from_session', 20, 3 );
function set_custom_cart_item_prices_from_session( $session_data, $values, $key ) {
    if ( ! isset( $session_data['new_price'] ) || empty ( $session_data['new_price'] ) )
        return $session_data;

    // Get the new calculated price and update cart session item price
    $session_data['data']->set_price( $session_data['new_price'] );

    return $session_data;
}

最后点击你的自定义网址

<button onclick="window.location.href='https://yourdomain.com/?add-to-cart=362166&quantity=1';">Add to cart</button>

【讨论】:

  • 添加到购物车 URL 应该使用 WooCommerce 函数生成
  • @Raptor,感谢您的评论,我知道,但我根据他们的要求发表评论。
  • 建议我使用“woocommerce_product_get_price”过滤器并修改返回值。 &lt;?php echo $row['purchase-price'] ?&gt; 是从 mysql 数据库查询中的值获得的。问题是我还不知道如何将其放入代码中。
  • @RosalitoUdtohan 我已经更新了我的答案。你在找这个吗?
猜你喜欢
  • 2021-05-19
  • 2019-12-25
  • 2020-10-29
  • 2018-10-30
  • 1970-01-01
  • 2022-01-18
  • 2017-05-12
  • 2018-01-31
  • 1970-01-01
相关资源
最近更新 更多