BuddyPress Tutorial: Redirect users on their first login
Want to redirect users on their first login to some specific page on a BuddyPress site? This tutorial is your guide to login redirection.
Let us see a few reasons why you might want to redirect your users on their first login.
- You may want to help them understand site features by sending to some guide page
- You may want to send them to their profile
- You may want to send them to some twitter like friends suggestions/group suggestions page.
- … and you may have some other better reason to do so.
Once we agree that user should be redirected to somewhere, We need to add the code to our functions.php in theme or bp-custom.php
WordPress provides a filter "login_redirect" which allows us to change the url where the user should be redirected after login. You can do a lot of fun stuff with this filter. You can redirect users to different urls by their member type or roles or geo location or some other criteria as you please.
For this tutorial, our only concern is first login of the user.
Strategy:- Detecting first login of the user
BuddyPress stores user's last active time if they have logged in to the site before.
From the above statement, we can safely deduce that if the last active time of the user who is logging in is empty, it must be their first login.
Here is an example code to redirect user to their BuddyPress profile on first login
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | function buddydev_redirect_on_first_login( $redirect_to, $redirect_url_specified, $user ) { //check if we have a valid user? if ( is_wp_error( $user ) ) { return $redirect_to; } //check for user's last activity $last_activity = bp_get_user_last_activity( $user->ID ); if ( empty( $last_activity ) ) { //it is the first login //update redirect url //I am redirecting to user's profile here //you may change it to anything $redirect_to = bp_core_get_user_domain($user->ID ); } return $redirect_to; } add_filter( 'login_redirect', 'buddydev_redirect_on_first_login', 110, 3 ); |
That's all. Have fun building your BuddyPress community 🙂
Any way to do this only for contributors?
Yes, sure. All you need to do is check for the cap using user_can() and use the cap from here
https://codex.wordpress.org/Roles_and_Capabilities#Capability_vs._Role_Table
to detect the capability.
If you need complete code, Please post in our forum.
Regards
Brajesh