从WooCommerce的税类过滤器挂钩中排除特定的产品变化

时间:2020-10-12 15:07:28

标签: php wordpress woocommerce tax product-variations

我正在尝试通过wordpress过滤器中的角色来应用特定的税种。此税种适用于变体产品以及常规的单一产品。我只需要按ID排除特定的变化产品或生产变化。 这是我到目前为止的内容:

 function wc_diff_rate_for_user( $tax_class, $product ) {
  $user_id = get_current_user_id();
  $user = get_user_by( 'id', $user_id );
  if ( is_user_logged_in() && ! empty( $user ) && in_array( 'MEMBER', $user->roles ) &&  is_product() && get_the_id() != 1337)   {
    $tax_class = 'Reduced rate';
  }
  return $tax_class;
 }
 add_filter( 'woocommerce_product_get_tax_class', 'wc_diff_rate_for_user', 1, 2 );
 add_filter( 'woocommerce_product_variation_get_tax_class', 'wc_diff_rate_for_user', 1, 2 );

我认为我在以下部分上失败了: is_product() && get_the_id() != 1337) 因为“降低税率”的税种适用于所有产品,包括试图排除的产品。 任何建议将不胜感激。

1 个答案:

答案 0 :(得分:0)

代码中的主要问题是get_the_id()在单个可变产品页面上不能用于产品变体,因为它提供了可变产品ID,但没有任何产品版本ID ...

与在代码中看到的相反,钩子函数具有2个可用参数,因此您可以使用变量$product使用方法get_id()从其获取ID,如下所示:

add_filter( 'woocommerce_product_get_tax_class', 'change_tax_class_user_role', 10, 2 );
add_filter( 'woocommerce_product_variation_get_tax_class', 'change_tax_class_user_role', 10, 2 );
function change_tax_class_user_role( $tax_class, $product ) {
    $excluded_variation_id = 1337;
    $targeted_user_role    = 'MEMBER';

    if ( $product->is_type('variation') && $product->get_id() == $excluded_variation_id ) {
        return $tax_class;
    } 
    elseif ( current_user_can( $targeted_user_role ) ) {
        return 'Reduced rate';
    }
    return $tax_class;
}

代码进入活动子主题(或活动主题)的functions.php文件中。应该可以。