首页 > 解决方案 > 用户角色的 Woocommerce 折扣

问题描述

编辑:如你所见,我是新来的。很抱歉让您头疼这是目前的问题:代码现在正在运行!但是,当商店页面上的产品价格与购物车和结帐页面不同时,这可能与税收有关。

为了清楚起见,我已插入不含增值税的价格,并且在商店页面上不含增值税。但在购物车页面上计算增值税。

概括:

商店页面 – 快速打开购物车

我目前正在使用 Wordpress + Woocommerce 进行一个非常复杂的项目,并且我对 PHP 和 Wordpress/Woocommerce 钩子不太熟悉。我正在尝试对 X 类产品应用百分比折扣。我遇到了类似的问题

遇到非数值

在仪表板上,价格与购物车/结帐页面上的产品存档页面不同。

这是我在functions.php上的代码:

add_filter('woocommerce_product_variation_get_price', 'custom_price', 10, 2);
add_filter('woocommerce_product_get_price', 'custom_price', 10, 2);
add_filter('woocommerce_get_price', 'custom_price', 10, 2);

function custom_price($price, $product)
{
  if (!is_user_logged_in()) return $price;

  if (has_role('hintaluokka-5')) {
    $price = $price * 0.95;
  } elseif (has_role('hintaluokka-12')) {
    $price = $price * 0.88;
  } elseif (has_role('hintaluokka-15')) {
    $price = $price * 0.85;
  } elseif (has_role('hintaluokka-22')) {
    if (has_term('kastikkeet', 'product_cat', $product->ID)) {
      $price = $price * 0.78;
    } else {
      $price = $price * 0.9;
    }
  }
  return $price;
}

function has_role($role = '', $user_id = null)
{
  if (is_numeric($user_id))
    $user = get_user_by('id', $user_id);
  else
    $user = wp_get_current_user();

  if (empty($user))
    return false;

  return in_array($role, (array) $user->roles);
}

标签: phpwordpresswoocommerce

解决方案


试试这个代码:

add_filter( 'woocommerce_product_variation_get_price', 'custom_price', 10, 2 );
add_filter( 'woocommerce_product_get_price', 'custom_price', 10, 2 );
function custom_price( $price, $product ) {
    if ( ! is_user_logged_in() ) {
        return $price;
    }

    if ( has_role( 'hintaluokka-5' ) ) {
        $price *= 0.95;
    } elseif ( has_role( 'hintaluokka-12' ) ) {
        $price *= 0.88;
    } elseif ( has_role( 'hintaluokka-15' ) ) {
        $price *= 0.85;
    } elseif ( has_role( 'hintaluokka-22' ) ) {
        if ( has_term( 'kastikkeet', 'product_cat', $product->ID ) ) {
            $price *= 0.78;
        } else {
            $price *= 0.9;
        }
    }

    return $price;
}

function has_role( $role = '', $user_id = null ) {
    if ( is_numeric( $user_id ) ) {
        $user = get_user_by( 'id', $user_id );
    } else {
        $user = wp_get_current_user();
    }

    if ( empty( $user ) ) {
        return false;
    }

    return in_array( $role, $user->roles, true );
}

我认为这里没有什么大问题。只有一个钩子不再使用(已弃用)。

如果这没有帮助,请发布错误消息。


推荐阅读