I want to change the home page url of wordpress site to another url when the user is logged in and have a specific role. Is this possible?
Thanks in advance.
What do you consider to be the home page?
Do you want to change what is answering on the /
url on your website?
If so, I think that you can use the init
hook and use wp_redirect()
function to send your user wherever you want based on the result of wp_get_current_user()
result.
Something like that.
add_action('init', function () {
if ($user = wp_get_current_user()) {
if (in_array('my-custom-role', $user->roles)) {
wp_redirect('/my-custom-url');
}
}
});
init
can be too late for this, I think template_redirect
is the recommended hook for redirection.
init
has been called before template_redirect
, but you're right that the WP code reference shows to use this one.
Yes, this absolutely is possible. There are a couple of steps that you would need to take to get this working;
is_front_page
function for this, you may need to use is_home
or even both depending on your configuration and requirements.is_user_logged_in
function to check that they are.wp_get_current_user
wp_safe_redirect
for this as it would ensure that the url you are redirecting to is one that belongs to your site.This is then called on the init
hook as that ensures some of the methods and data will be available, such as the current user, and allow the redirect to happen as soon as possible.
A full example may look like the following:
function redirect_from_front_page() {
$redirect_url = '/example/url'; // Change this to the path or url you wish to redirect to.
$expected_role = 'custom-role'; // Change this to the role you would like to redirect based on.
/**
* Check that the user is on the front page
* before continuing.
*/
if( ! is_front_page() ) {
return;
}
/**
* Check that the user is logged in.
*/
if( ! is_user_logged_in() ) {
return;
}
/**
* Get the currect user roles.
*/
$user = wp_get_current_user();
$roles = $user->roles;
/**
* If the user has a role that matches the expected role
* redirect to the given page.
*/
if ( in_array( $expected_role, $roles ) ) {
wp_safe_redirect( $redirect_url );
exit;
}
}
add_action( 'init', 'redirect_from_front_page' );