首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用woocommerce_product_get_price钩子检查价格问题

使用woocommerce_product_get_price钩子检查价格问题
EN

Stack Overflow用户
提问于 2017-12-13 08:08:16
回答 1查看 6.7K关注 0票数 3

我需要加倍的价格,每一个产品在吴商业前端。为此,我使用了以下代码:

代码语言:javascript
运行
复制
add_filter( 'woocommerce_product_get_price', 'double_price', 10, 2 );
function double_price( $price, $product ){
    return $price*2;
}

但是使用此代码时出现了错误。退房页面价格不正确。例如,产品的原价是10,按此代码计算,价格是原来的两倍。所以现在的产品价格是20美元。当我把这个产品添加到购物车中时,购物车和结账页面的价格是40。这意味着这种乘法是在两次之间发生的。

请帮我解决这个问题。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-12-13 08:33:57

更新了,将价格提高一倍:

1)首先,您将限制您的代码仅限于单个产品和存档页面:

代码语言:javascript
运行
复制
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() )
        return $price*2;

    return $price;
}

2)然后,对于购物车和结账页,您将按以下方式更改购物车项目的价格:

代码语言:javascript
运行
复制
add_filter( 'woocommerce_add_cart_item', 'set_custom_cart_item_prices', 20, 2 );
function set_custom_cart_item_prices( $cart_data, $cart_item_key ) {
    // Price calculation
    $new_price = $cart_data['data']->get_price() * 2;

    // 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;
}

代码在您的活动子主题(或主题)的function.php文件中,或者在任何插件文件中。

测试和工作。它将按照您在购物车、结帐和订购页面…中所期望的那样改变所有价格。

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47788254

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档