简体   繁体   中英

Wordpress function - is_user_logged_in() is always returning false

I set up my htaccess file to redirect to a PHP script when users try to access /wp-content/uploads/2020/05/test.pdf. The PHP script is in my root directory. The redirect works just fine. In the script, I have the following code:

require_once('wp-load.php');

if (is_user_logged_in()) {
    wp_redirect('https://mywesbite.com/page1/');
    exit;
} else {
    wp_redirect('https://mywesbite.com/page2/');
    exit;
} 

I tested this on a few different Wordpress websites and in two of them it works as expected. If the user is logged in they will go to page1. However, on the website that I need it to work for, it always takes them to page2. I've tried deactivating all the plugins and changing the theme to the same as the websites the code works with. Still doesn't work. This makes me think it has something to do with the server setup. It's on Managed WordPress through GoDaddy. Is it possible that there is some server configuration that is preventing it from working correctly like the other websites? That's the only difference that I can think of.

I found out the login cookie was not being recognized in the PHP script. I suspect that it has something to do with the server setup, but couldn't pinpoint the issue.

I did however find a workaround. Rather than having the script located in the root directory, you can create a template file within your child theme and have the script there. Then have the redirect point to a page you create with the template. Everything worked as expected once I made this change.

<?php
/**
 * Template Name: Redirect Template
 *
 */

if (is_user_logged_in()) {
    wp_redirect('https://mywesbite.com/page1/');
    exit;
} else {
    wp_redirect('https://mywesbite.com/page2/');
    exit;
}

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM