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.

1
1

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

Leave a Reply

Your email address will not be published. Required fields are marked *