plugins - Conditional Homepage for logged in user

admin2025-01-07  6

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.

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.

Share Improve this question asked Jun 25, 2020 at 11:20 Nayan ChowdhuryNayan Chowdhury 33 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 1

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');
        }
    }
});

Yes, this absolutely is possible. There are a couple of steps that you would need to take to get this working;

  1. Check that the user is currently on the front page, you can use the is_front_page function for this, you may need to use is_home or even both depending on your configuration and requirements.
  2. Check that the user is currently logged in, you can use the is_user_logged_in function to check that they are.
  3. Get the user roles. These can be retrieved from the object returned by wp_get_current_user
  4. Check that the user has the expected role.
  5. Redirect. You should use 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' ); 
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736252093a18.html

最新回复(0)