5

I need to redirect logged-in and non-admin users, from page with id 172, to the home of the website. Note that users that are not logged in can actually see the page.

add_action('admin_init', 'xyz');
function xyz() {
    if( is_page( 172 ) ) {
             if( is_user_logged_in() && ! current_user_can('update_core') ) {
        wp_redirect( home_url() );
        exit;
             }
    }   
}

Problem: This code is not working.

5

admin_init runs on admin pages, not the front end. The equivalent front end action, init, is too early to check is_page. A safe action for redirection is template_redirect:

function xyz() {
    if( is_page( 172 )
        && ! current_user_can('update_core') ) {
            wp_redirect( home_url() );
            exit;
    }   
}
add_action( 'template_redirect', 'xyz' );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.