简体   繁体   中英

How can I get the current Wordpress e-mail address of a logged-in user in an external php file?

I have the following issue. I want to load the Wordpress environment into an external php file. All my work is currently on a localhost and my php code is as follows:

<?php
require("../../wp-blog-header.php");

$admin = do_shortcode("[su_user field='user_email']");

if ($admin === "admin@email.com") {

    // Do stuff here

}

else {

    echo "<h1>Forbidden.</h1>";

}

This works perfectly fine in my localhost, so I figured that when I upload the file to the server it must work too, given that the file is stored in the same directory as it is locally, hence ../../wp-blog-header.php . Sadly, this does not work. When I echo $admin; the following error appears:

User: user ID is incorrect

I tried using the native Wordpress functions without using the shortcode like this:

<?php global $user_email;
      get_currentuserinfo();

      echo $user_email;
?>

This does not work either. Is there a more efficient way to load the Wordpress environment into an external php file? Any suggestions on what is happening here? It does not necessarily have to be an e-mail, it could be the user id as well, which I tried and gives me 0.

I forgot to mention, the php file loads and echoes Forbidden together with the error. This makes me believe that the file require("../../wp-blog-header.php") is actually being loaded because when I change the directory I directly get an error that the file is now working/available.

The shortcode works as I have tested it inside a new Page returning the e-mail address of the logged-in user.


UPDATE

My root is:

/var/www/vhosts/test-website.com/httpdocs/

Which I tested with require("/var/www/vhosts/test-website.com/httpdocs/wp-blog-header.php") as well. Still same result. The weird thing is that if I add wp_head() below this line, the header gets loaded. I reformulate my question:

How can I get the current e-mail address of a logged-in user in an external php file?

If your file is same folder root with Wordpress instance. just use code bellow:

<?php
define( 'ROOT_PATH', dirname(__FILE__) );
require(ROOT_PATH . "/wp-blog-header.php");

//your stuff

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