Forums

[resolved] Checking user login state from a non-wp file (4 posts)

  1. caemusic
    Member
    Posted 3 years ago #

    For certain reasons I do not want the home page of my site to be a wordpress driven page, but I would like to check if the user is logged in to display the login/logout link properly.

    In the index.php file in my root directory, I first do this without getting any errors (cae is the directory of my blog):

    <?php
    require("cae/wp-load.php");
    ?>

    Then I tested the following sample code found in the WP function reference:

    <?php  if (is_user_logged_in()){
               echo "Welcome, registered user!";
             }
             else {
               echo "Welcome, visitor!";
               };
    ?>

    The result is that I get "Welcome, visitor!" every time regardless of whether the user is logged in.

    Any ideas on how this can be done successfully with a non-wordpress page? Is there a different php file I need to include?

    Thanks!

  2. Otto
    Tech Ninja
    Posted 3 years ago #

    In the index.php file in my root directory, I first do this without getting any errors (cae is the directory of my blog):

    The user is not "logged in" because they didn't pass the proper cookie.

    The cookie has a path. In your case, that path is "/cae". Since you're requesting from another path (root, or "/"), then the login cookie is not passed to the script. Therefore, since you didn't pass the cookie, you didn't authenticate, and are not logged in.

    That trick only works for subdirectories underneath the WordPress install, which is to say it works best when WordPress is at the root of the website.

    You could try redefining "COOKIEPATH" in your wp-config.php file. That will let you change what the path of the auth cookies is to the root path, so that the cookie gets passed along to your entire site.

  3. caemusic
    Member
    Posted 3 years ago #

    Thank for the tip Otto! I was actually able to find a plugin to change the cookie location:

    http://wordpress.org/extend/plugins/root-cookie/

    However, it looks like it should be easy to do this without a plugin. I'll give it a shot and update this thread so people that like to tinker know how it can be done.

  4. caemusic
    Member
    Posted 3 years ago #

    Ok, there's a little more to it than I originally expected. For example, there are different kinds of cookies for different kinds of users. To avoid breaking something I'd suggest using the plugin. Additionally, you can use the plugin php file to change the cookie lifespan, if that sort of thing interests you.

    Great success!

Topic Closed

This topic has been closed to new replies.

About this Topic