I have set up a custom user role with a slug of performance_customer
. I am checking to see if the current user is a "performance customer" and apply certain price discounts to products in specific categories.
Here is my code:
function return_custom_performance_dealer_price($price, $product) {
global $woocommerce;
global $post;
$terms = wp_get_post_terms( $post->ID, 'product_cat' );
foreach ( $terms as $term ) $categories[] = $term->slug;
$origPrice = get_post_meta( get_the_ID(), '_regular_price', true);
$price = $origPrice;
//check if user role is performance dealer
$current_user = wp_get_current_user();
if( in_array('performance_customer', $current_user->roles)){
//if is category performance hard parts
if(in_array( 'new-hard-parts-150', $categories )){
$price = $origPrice * .85;
}
//if is category performance clutches
elseif(in_array( 'performance-clutches-and-clutch-packs-150', $categories )){
$price = $origPrice * .75;
}
//if is any other category
else{
$price = $origPrice * .9;
}
}
return $price;
}
add_filter('woocommerce_get_price', 'return_custom_performance_dealer_price', 10, 2);
The function works perfectly in the product loop, but when I added a product to the cart it blew up and gave me this error for each line containing if(in_array( 'CATEGORY_NAME_HERE', $categories )){
.
Error: Warning:
in_array()
expects parameter 2 to be array, null given in…
I'm guessing this has to do with the 5th line of the code above where I use wp_get_post_terms()
to form an array of the categories that each product belongs to. I'm not sure how to make this work.
First, the filter hook woocommerce_product_get_price
is now replacing deprecated hook woocommerce_get_price
…
To avoid the error you got you should use Wordpress conditional dedicated function has_term()
I have revisited your code a bit, so please try this instead:
add_filter('woocommerce_product_get_price', 'return_custom_performance_dealer_price', 10, 2);
function return_custom_performance_dealer_price( $price, $product ) {
$price = $product->get_regular_price();
//check if user role is performance dealer
$current_user = wp_get_current_user();
if( in_array('performance_customer', $current_user->roles) ){
//if is category performance hard parts
if( has_term( 'new-hard-parts-150', 'product_cat', $product->get_id() ) ){
$price *= .85;
}
//if is category performance clutches
elseif( has_term( 'performance-clutches-and-clutch-packs-150', 'product_cat', $product->get_id() ) ){
$price *= .75;
}
//if is any other category
else{
$price *= .9;
}
}
return $price;
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
Tested for WooCommerce 3+… It should work now…