Is it possible to add Group/Role/User Specific cart discount rule ranges?

It is possible with the help of the hook ‘csp_filter_cart_discount_limits’.

The following steps will show how you can apply group-based cart discounts.

  • Let us say the following is our array of cart-discount rules for the groups.
$groups_cart_prices =  array(
			//This can have multiple arrays of groups.
'Registered'   => array(
				//This can have multiple arrays of rules.
				array('min' => '10','max' => '50','discount' => '50',),
				array('min' => '50','max' => '500','discount' => '20',),
			),
'Wholesellers' => array(
				//This can have multiple arrays of rules.
				array('min' => '100', 'max' => '500', 'discount' => '30'),
				array('min' => '501', 'max' => '999', 'discount' => '40')),
				);
  • To apply these different rules for the users having different groups you can use the filter as shown below.
function applyGroupBasedCartPrice( $rules ) {
		$groups_cart_prices =  array(
'Registered'   => array(
				array('min' => '10','max' => '50','discount' => '50',),
				array('min' => '50','max' => '500','discount' => '20',),
			),
'Wholesellers' => array(
				array('min' => '100', 'max' => '500', 'discount' => '30'),
				array('min' => '501', 'max' => '999', 'discount' => '40')),
				);

		foreach ($groups_cart_prices as $key => $value) {
			// Flag to check whether the user is present in the group or not.
			$is_a_member = false;
			// Checks whether a group exists or not.
			if ( Groups_Group::read_by_name( $key ) ) {
				// get group details.
				$group = Groups_Group::read_by_name( $key );
				// check user present in group or not
				$is_a_member = Groups_User_Group::read( get_current_user_id() , $group->group_id );
			}
			// if present then return array of rules for respected groups
			if ( $is_a_member ) {
				return $value;
			}
		}
		//default return.
		return $rules;
	}
}
add_filter( 'csp_filter_cart_discount_limits', 'applyGroupBasedCartPrice', 99, 1);

Updated on July 1, 2020

Was this article helpful?

Related Articles