最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Redirect logged on user to a specific page based on wp user role, page id

programmeradmin4浏览0评论

I am trying to redirect users(subscribers) to a particular page based on the following conditions 1. (subscriber) user is logged on 2. specific page id is matched 3. wp user role = subscriber which is the default role set when a user is registered on the platform

The Challenge i am having is conditions 1 and 2 works but not 3.

Here is my code:

function add_login_check()
{
    if ( is_user_logged_in() && is_page(1865)) {
        wp_redirect('');
        exit;
    }
}
add_action('wp', 'add_login_check');

Interesting enough when i tested the above code using administrator role it works as expected but with subscriber role i get redirected automatically to the subscriber profile page upon logon.

I am trying to redirect users(subscribers) to a particular page based on the following conditions 1. (subscriber) user is logged on 2. specific page id is matched 3. wp user role = subscriber which is the default role set when a user is registered on the platform

The Challenge i am having is conditions 1 and 2 works but not 3.

Here is my code:

function add_login_check()
{
    if ( is_user_logged_in() && is_page(1865)) {
        wp_redirect('http://destredirectedpage.php');
        exit;
    }
}
add_action('wp', 'add_login_check');

Interesting enough when i tested the above code using administrator role it works as expected but with subscriber role i get redirected automatically to the subscriber profile page upon logon.

Share Improve this question edited Jan 21, 2021 at 2:47 fuxia 107k38 gold badges255 silver badges459 bronze badges asked Jan 21, 2021 at 1:31 john zuhjohn zuh 254 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 1

We can check the $request which is passed to our login_redirect filter-function using url_to_postid.

// redirect subscribers if logging in from specific page
function wpse381872_login_redirect( $redirect_to, $request, $user ) {

    // turn the request url into a post-id
    $request_id = url_to_postid( $request );

    if ( isset( $user->roles ) && is_array( $user->roles ) ) {
        // check for subscribers logging in via 1865
        if ( 1865 === request_id && in_array( 'subscriber', $user->roles ) ) {
        
            $redirect_to = 'http://destredirectedpage.php';
            
        }
    }

    return $redirect_to;
}

add_filter( 'login_redirect', 'wpse381872_login_redirect', 10, 3 );

Another work around is by using current_user_can, considering the permissions that a specific role has. Assuming that subscribers can edit posts, one can do the following

function add_login_check()
{
    if (is_user_logged_in()  && !current_user_can('edit_posts')) {
        if (is_page(1865)){
            wp_safe_redirect( get_permalink('447'));
            exit; 
        }
    }
}
发布评论

评论列表(0)

  1. 暂无评论