is_user_logged_in returns false when I access certain pages


I’m working on a single page application built with WordPress and Vue.js, I used add_rewrite_rule to redirect all sub-pages of projects/ to index.php. Only logged-in users can access the application. If a user isn’t logged-in a redirect to wp-login.php will be returned.

Here’s the code I used in functions.php to achieve what I mentioned above:

// Redirect users who are not logged-in
add_action('template_redirect', function () {

    // Front end only and allow access to ajax functions
    if (is_admin() || wp_doing_ajax()) {

    // Redirect all pages to the login page if user isn't logged in
    if (!is_user_logged_in()) {

// Remove all default WP template redirects/lookups
remove_action('template_redirect', 'redirect_canonical');

add_action('init', function () {
    // Redirect homepage or all requests that start with /projects to index.php so the Vue app
    // is loaded and 404s aren't thrown
    add_rewrite_rule('^projects((/.*)?)', 'index.php', 'top');

The issue is whenever I access any sub-page /projects/page/etc I do get redirected to wp-login.php even though I’m logged in! And the strange thing is this happens only on the production server, development and staging servers all work fine.

I used a var_dump(is_user_logged_in()) inside the callback of the template_redirect action and the result is false.

, Kerkouch 3 years 2020-07-03T13:10:34-05:00 0 Answers 63 views 0

Leave an answer