get_current_user_id() returning Zero 0

get_current_user_id() is returning 0 for following codes. I do tried some solution available on stack overflow but somehow not working for me. I’m expecting explanation why its returning zero and how to fix?

P.S: I’m calling get_current_user_id() from external php page and included '../wp-blog-header.php' for that.

Read More

Code:

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

$user_ID = get_current_user_id(); 
echo $user_ID;

?> 

Related posts

3 comments

  1. You have to call wordpress proccess of user authentication. Try adding the following code before get_current_user_id();, if it doesn’t solve your problem it’ll at least point you the right direction:

    $user_id = apply_filters( 'determine_current_user', false );
    wp_set_current_user( $user_id );
    

    Hope it helps!

  2. This is likely a result of including wp-blog-header.php directly in your external file. From the Codex on get_current_user_id():

    The user’s ID, if there is a current user; otherwise 0.

    I’m not sure what you’re trying to do, but the correct method would be to add this logic to functions.php under the correct action hook, or by writing a custom plugin. By doing one of those two things, you will have access to the authenticated user.

  3. if you are using ajax then may be in some browser versions we can’t get id by get_current_user_id() for this we can use xhrFields in over ajax then it will work fine. if the problem with the browser version.

            jQuery.ajax({
                type: "POST",
                xhrFields: {
                    withCredentials: true
                },
                cache: false,
    

Comments are closed.