[UTILS] Retrieve Customer Balance by ID
-
Good day everyone!
I love the plugin and the efforts made by Josh and the Advanced Coupons team! I’m using AC in my store and had a little fun time personalizing some functionalities to tailor it better to my needs, today i wanted to share one that i think is quite useful with you, so this is not actually a help request ??
First a little disclaimer: i am not a professional therefore i suggest you test the code in a staging environment first, i am not responsible for damages or issues caused to your website because of the use of code i’m providing here. I am also not sure this is the best way to do it, but it is what i can do and it works for me ??
Here is my code for your functions.php to create a custom function that makes retrieving a customer balance easier
//get unformatted user balance by ID function get_user_balance($user_id) { $user_balance = apply_filters( 'acfw_filter_amount', \ACFWF()->Store_Credits_Calculate->get_customer_balance( $user_id ) ); return $user_balance; }
With this you can now use it anywhere in your code by simply calling get_user_balance(ID);
For example i used it in combination with Advanced Custom Fields to show the customer balance in the woocommerce order edit page:
//load the balance in the ACF field //MAKE SURE TO CHANGE YOUR FIELD KEY function update_store_credit_order_admin($value) { global $post; $customer_user = get_post_meta( $post->ID, '_customer_user', true ); $value = '€ '.get_user_balance($customer_user); return $value; } add_filter('acf/load_value/key=YOUR_FIELD_KEY', 'update_store_credit_order_admin', 10, 1);
But of course we could also create a custom shortcode to show it anywhere in your theme – in this case [user_balance]
//[user_balance] shortcode for Advanced Coupons function user_balance_shortcode($atts) { $current = get_current_user_id(); $default = array( 'user' => $current, 'desc' => 'Balance: € ', 'nologin' => '' ); $a = shortcode_atts($default, $atts); if ($a['user'] == 0) { return $a['nologin']; } return $a['desc'].get_user_balance($a['user']); } add_shortcode('user_balance','user_balance_shortcode');
And by doing so you can use the shortcode in many ways:
- the [user_balance] shortcode will print out the current user balance, useful to show your logged in users their own balance in other places of your theme other than the provided page in the profile
- you can provide the user ID with a shortcode attribute to show a specific user’s balance like so: [user_balance user=”58″]
- you can provide a custom description to show before the balance like so: [user_balance desc=”Here’s your balance: “]
- if the user is not logged in the [user_balance] shortcode won’t show anything, but you can set it to show a custom message instead by simply setting a nologin attribute: [user_balance nologin=”Login to show your balance”]
Let me know how it works for you, hope it helps ??
Cheers!!
- The topic ‘[UTILS] Retrieve Customer Balance by ID’ is closed to new replies.