简体   繁体   English

WordPress-检查用户是否从外部PHP文件登录

[英]WordPress - Check if user is logged in from external PHP file

I'm trying to check if WordPress user is logged in or not from an external PHP file and here is my code 我正在尝试检查WordPress用户是否已从外部PHP文件登录,这是我的代码

<?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? 该自定义php文件何时加载? According to the Action Reference - You need to wait until at least the init hook before the user is authenticated. 根据《 Action Reference -您需要至少等到init钩子之后才能对用户进行身份验证。

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. 我以为您的代码是正确的,因此我对其进行了测试(仅更改“ require('../../ trading / wp-load.php');”行以匹配我的安装), 它可以按预期工作,因此代码本身就是正确,还有其他错误。

For WordPress (in a standard configuration) to know a user is logged it must receive a cookie. 为了使WordPress(在标准配置中)知道用户已登录,它必须接收cookie。 Can you add a 你能加一个

var_dump( $_COOKIE );

to your script and verify a cookie like ''wordpress_logged_in_ ...' is being received. 到您的脚本,并验证是否已收到“ wordpress_logged_in_ ...”之类的Cookie。

WordPress has hooks so user verification can be customised. WordPress具有挂钩,因此可以自定义用户验证。 Of course in a customised installation the above may not be true. 当然,在定制安装中,上述内容可能并不正确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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