woocommerce:根据城市选择,展示不同价格的产品


woocommerce: Display products with different price according to city selection

我想添加一个弹出框,当你点击并去商店页面,其中用户选择的城市。一旦选择了城市,我希望显示用户所选城市特定价格的产品。

您是想为每个城市的每个产品指定确切的价格,还是可以编写简单的规则,可以应用于基于城市的原始价格(例如,将低10%四舍五入到最接近的偶数)?

如果要指定每个城市中每个产品的价格,则为所有产品的所有城市创建元字段。Dez链接到的指南很好,所以我将在这里重用它。

首先为指定城市的用户设置一个cookie。有很多方法可以获得城市价值,我不知道你更喜欢哪种方法。

setcookie("city", $city, time() + 315360000);

然后使用这个过滤器覆盖显示给用户的价格:

add_filter('woocommerce_get_sale_price', 'my_custom_price', 99, 2);
add_filter('woocommerce_get_price', 'my_custom_price', 99, 2);
function my_custom_price( $orginal_price, $product )
{
    //Get the cooke value
    $city = $_COOKIE["city"];
    //your logic for calculating the new price based on city here
    switch ($city) {
        case 'new_york':
            $new_price = round($orginal_price * 0.95); //Calculate the price (here 5% discount)
            break;
        default:
            $new_price = $orginal_price
            break;
    }
     //OR just: 
     $new_price = get_post_meta( $product->ID, 'wc_price_'.$city, true ); //Retrieve the price from meta value 
     //If no matching price is found, return original price
     if( ! empty( $new_price ) ) {
         return $orginal_price;
     } 
    //Return the new price (this is the price that will be used everywhere in the store)
    return $new_price;
}

但是在使用此解决方案时要注意缓存。那可能会引起一些麻烦。

对于这个特定的示例,有很多代码要编写,所以我将重点介绍您可以做的事情。

<标题>选项1
  1. 当用户选择一个城市时,设置一个包含该城市名称或city_id的cookie
  2. 为匹配城市名称或city_id的产品创建自定义字段(这里是一个指南)
  3. 如果用户没有在cookie中设置城市,则隐藏价格
  4. 自定义templates/single-product/price.php模板以显示映射到其城市的价格
  5. 当他们将产品添加到购物车时,覆盖产品的价格(这里有一个指南)
<标题>选项2 h1> li>使用WooCommerce动态定价
  • 要求一个人在向购物车中添加产品之前注册,并将城市作为注册字段
  • 根据他们对城市的回答将他们置于动态定价定义的角色
  • 警告:我不确定动态定价选项是否适合您想要的,因为我认为它根据用户角色在购物车中显示折扣,而不仅仅是调整商品的价格。