I'm trying to check if WordPress user is logged in or not from an external PHP file and here is my code
<?php
/*Load up wordpress externally*/
define( 'WP_USE_THEMES', false );
define( 'COOKIE_DOMAIN', false );
define( 'DISABLE_WP_CRON', true );
require('../../trading/wp-load.php');
if ( is_user_logged_in() ){
$user = wp_get_current_user();
print_r($user);
}else{
echo 'logged out';
}
?>
I always get 'logged out' message, even though the user is logged in. Any idea how can I fix this?
Thanks
When is this custom php file loaded? According to the Action Reference
- You need to wait until at least the init
hook before the user is authenticated.
I would try:
add_action( 'init', 'FDI_logged_in' );
function FDI_logged_in(){
if( is_user_logged_in() ){
$user = wp_get_current_user();
print_r( $user );
} else {
echo 'logged out';
}
}
I thought your code was correct so I tested it (changing only the line "require('../../trading/wp-load.php');" to match my installation) and it worked as expected so code itself is correct and something else is wrong.
For WordPress (in a standard configuration) to know a user is logged it must receive a cookie. Can you add a
var_dump( $_COOKIE );
to your script and verify a cookie like ''wordpress_logged_in_ ...' is being received.
WordPress has hooks so user verification can be customised. Of course in a customised installation the above may not be true.
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.