I have a custom PHP file on which I want to use some WordPress functions such as wp_get_current_user(). I've tried requiring wp-load.php, but that increases the load time significantly as it loads all WP functions.
Is there anyway I can use only the functions I need from WP?
Thanks, Emir
I have a custom PHP file on which I want to use some WordPress functions such as wp_get_current_user(). I've tried requiring wp-load.php, but that increases the load time significantly as it loads all WP functions.
Is there anyway I can use only the functions I need from WP?
Thanks, Emir
You may be able to have Wordpress push data to the session or to your custom PHP, rather than trying to load Wordpress each time you need to query some the user. I'm not sure what other functions you want to call.
The alternative is to use the Wordpress REST API, take a look at the authentication section.
No.
Most WordPress methods require a working WordPress backend to run. Let's take a look at wp_get_current_user
as an example:
function wp_get_current_user() {
return _wp_get_current_user();
}
Which leads us to _wp_get_current_user
:
function _wp_get_current_user() {
global $current_user;
if ( ! empty( $current_user ) ) {
if ( $current_user instanceof WP_User ) {
return $current_user;
}
// Upgrade stdClass to WP_User
if ( is_object( $current_user ) && isset( $current_user->ID ) ) {
$cur_id = $current_user->ID;
$current_user = null;
wp_set_current_user( $cur_id );
return $current_user;
}
// $current_user has a junk value. Force to WP_User with ID 0.
$current_user = null;
wp_set_current_user( 0 );
return $current_user;
}
if ( defined('XMLRPC_REQUEST') && XMLRPC_REQUEST ) {
wp_set_current_user( 0 );
return $current_user;
}
/**
* Filters the current user.
*
* The default filters use this to determine the current user from the
* request's cookies, if available.
*
* Returning a value of false will effectively short-circuit setting
* the current user.
*
* @since 3.9.0
*
* @param int|bool $user_id User ID if one has been determined, false otherwise.
*/
$user_id = apply_filters( 'determine_current_user', false );
if ( ! $user_id ) {
wp_set_current_user( 0 );
return $current_user;
}
wp_set_current_user( $user_id );
return $current_user;
}
We can see that WordPress does a lot "under the hood" to get the current user, so implementing this function as a standalone method probably wouldn't get you too far.
As suggested in the other answer by @AlexanderHolsgrove, the REST API is a good way to communicate to a WordPress install if you need to fetch/send data to WordPress from another application.
You should also take a look at the SHORTINIT
constant - if defined in your wp-config.php
, it loads certain parts of WordPress and then bails out. I'm not sure if it would load what you need, but it may be worth taking a look there.
$post
,$wp_query
and others. – jdm2112 Commented Feb 4, 2019 at 21:04