BuddyPress Private Message for Non Logged in Users
In this tutorial for BuddyPress, we will work on two things:-
- Show private message button on user profile even if the visitor is not logged in
- When the visitor click on the button, they get redirected to the login page. Once they log in, the visitor will be sent to the send message page with the initial user set as the reciever.
Seeing the action through screenshots:-
1. Non logged in user visiting other user's profile
2. Clicking on the private message button redirect to WordPress login page(note the redirect url)
3. As soon as the user logs in, gets redirected to compose message screen
Code:-
Here is the code that you can put in your bp-custom.php or in your theme's functions.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | /** * Filter on the private message button args to se it visible for * non logged in members. Also, setup the url for redirecting to login page * * @param mixed $args * * @return mixed */ function buddydev_filter_private_message_button_args( $args ) { //if the user is logged in, we don't need to do anything //Also, I am only handling it for profile buttons here if ( is_user_logged_in() || ! bp_is_user() ) { return $args; } $user_id = bp_displayed_user_id(); $args['must_be_logged_in'] = false; //show for non logged in too //and redirect to our custom url containing the user id $args['link_href'] = wp_login_url( site_url('?message-redirect=' . $user_id ) ); return $args; } add_filter( 'bp_get_send_message_button_args', 'buddydev_filter_private_message_button_args' ); /** * Redirect to the send message when the user logs in * */ function buddydev_redirect_to_send_message_on_login() { //make sure it is our url set in previous step if ( ! is_user_logged_in() || empty( $_GET['message-redirect'] ) ) { return ; } //redirect to PM $user_id = absint( $_GET['message-redirect'] ); //let us make sure that user exists $user = get_user_by('id', $user_id ); //can not PM to invalid user //also you should not send message to yourself if ( ! $user || $user->ID == bp_loggedin_user_id() ) { return ; } $url = bp_loggedin_user_domain() . bp_get_messages_slug() . '/compose/?r=' . $user->user_login ; bp_core_redirect( $url ); } add_action( 'bp_template_redirect', 'buddydev_redirect_to_send_message_on_login' ); |
The tutorial is a result of one of our members here (@tizianopitisci) asking me about showing the private message button for BuddyPress users even when the visitor is not logged in. If you found the code helpful, thank him 🙂
Very greate and useful tutorial. I think this function helps visitors to understand that the website put in connection the users, so they can see this feature unless they have not yet an account.
Thank you. Yes, I definitely believe it will be helpful 🙂
it´s working to me. thx a lot.
Thank you for the comment Juan .