Redirect logged in users if they are on a specific page

I’m trying to prevent a user access besides the admin to the registeration page and reset password page if they are already logged in. I have the following:

function redirect_loggedin_users() {
// Maybe use is_user_logged_in() instead?
if (!current_user_can('manage_options') && is_page(array(2090, 2092))) {
    wp_redirect(home_url());
            exit();
    }
}
add_action('init', 'redirect_loggedin_users');

I tested it and it’s not working. Can someone please assist me? Thanks.

Related posts

1 comment

  1. One problem is that you’re hooking in too early. Reference the Hooks API Action Reference. Template conditionals such as is_page() are only available after the query has been set up and parsed. The earliest action that you can usually safely rely on query conditionals is pre_get_posts. You’re hooking into init, which fires much earlier:

    • muplugins_loaded After must-use plugins are loaded
    • registered_taxonomy For category, post_tag, etc.
    • registered_post_type For post, page, etc.
    • plugins_loaded After active plugins and pluggable functions are loaded
    • sanitize_comment_cookies
    • setup_theme
    • load_textdomain For the default domain
    • after_setup_theme Generally used to initialize theme settings/options.
    • auth_cookie_malformed
    • auth_cookie_valid
    • set_current_user
    • init Typically used by plugins to initialize. The current user is already authenticated by this time.
    • widgets_init Used to register sidebars. This is fired at ‘init’, with a priority of 1.
    • register_sidebar For each sidebar and footer area
    • wp_register_sidebar_widget For each widget
    • wp_default_scripts (ref array)
    • wp_default_styles (ref array)
    • admin_bar_init
    • add_admin_bar_menus
    • wp_loaded After WordPress is fully loaded
    • parse_request Allows manipulation of HTTP request handling (ref array)
    • send_headers Allows customization of HTTP headers (ref array)
    • parse_query (ref array)
    • pre_get_posts Exposes the query-variables object before a query is executed. (ref array)
    • posts_selection
    • wp After WP object is set up (ref array)
    • template_redirect
    • get_header
    • wp_enqueue_scripts

    Given the nature of what you’re trying to do, I would recommend hooking into template_redirect.

Comments are closed.