Skip to content

Instantly share code, notes, and snippets.

@jordymeow
Created June 5, 2023 13:29
Show Gist options
  • Save jordymeow/285e3d110742ce84f2bfb9252bf57a67 to your computer and use it in GitHub Desktop.
Save jordymeow/285e3d110742ce84f2bfb9252bf57a67 to your computer and use it in GitHub Desktop.
AI Engine: Modify the number of credits allowed for specific user(s) and/or role(s)
<?php
// The purpose of the mwai_stats_credits filter is to alter the number of credits (which can represent a certain number of queries or amount of dollars) allowed in total for a specific user.
// In this implementation below, we'll attribute the number of credits based on the role the user has.
add_filter( 'mwai_stats_credits', function ( $credits, $userId ) {
// Retrieve user data
$user = get_userdata( $userId );
// Assign the initial credits provided as argument
$credits_to_give = $credits;
// Check if the user has any roles
if ( !empty( $user->roles) && is_array( $user->roles ) ) {
// Loop over each role the user has
foreach ( $user->roles as $role) {
// If the user has the 'plus' role, assign them 100 credits
// This is our highest priority role - we don't need to check other roles once we find it
if ( $role === 'plus' ) {
$credits_to_give = 100;
break;
}
// If the user has the 'free' role and the 'plus' role has not been found,
// assign them 5 credits
// We only assign 'free' role credits if 'plus' role credits haven't been assigned already
if ( $role === 'free' && $credits_to_give != 100 ) {
$credits_to_give = 5;
}
}
}
// Return the calculated credits
// If no matching roles were found, this will be the default credits passed in as an argument
return $credits_to_give;
}, 10, 2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment