Through the get_current_user_id()
function we can obtain the ID of the user logged directly, without the need to completely manipulate the user
Wordpress object.
The problem that does not work ( has been said in the chat ) is because the OP I was running the code outside of the Wordpress environment .
To be inside the Wordpress environment, this would suffice:
echo get_current_user_id();
But, not being in the WP environment, we must include the wp-load
file, which will allow us to use the different Wordpress functions.
For example:
define( 'WP_USE_THEMES', false );
require ('wp-load.php'); //poner la ruta correcta donde se encuentra el archivo
echo get_current_user_id();
In the first line, what we are indicating is that it does not load the functions of the templates (which also loads wp-load
). If you also need those features, you can delete that line in the code.
For more details you can check the answers to the question: What is the correct way to use WordPress functions outside WordPress files? in the Wordpress area of StackExchange.