wp_get_current_user return ID = 0 when used outside of wordpress, such as webhook / fulfillment dialogflow

I want to get the user ID that is currently logged in.
I did it successfully when accessed via a web browser. However, when this function is called via dialogflow as webhook / fulfillment it always returns ID = 0.
This is my full code in PHP.

<?php

/** Absolute path to the WordPress directory. */
if ( !defined('ABSPATH') )
    define('ABSPATH', '/var/www/html/mine/');

/** Sets up WordPress vars and included files. */
require_once(ABSPATH . 'wp-config.php');

do_action( 'plugins_loaded' );

$current_user = wp_get_current_user();
 
$method = $_SERVER['REQUEST_METHOD'];

// Process only when method is POST
if($method == 'POST'){
    $requestBody = file_get_contents('php://input');
    $json = json_decode($requestBody);

    $action = $json->queryResult->action;
        
    if ($action == "ngopi"){
        if ($current_user->ID != 0){
            $ngopiResponse = "Hai..".$current_user->display_name;
        }
        else{
            $ngopiResponse = "Hai..Guest";  
        }   
    }
    
    $response = new stdClass();
    $response->speech = $ngopiResponse;
    $response->fulfillmentText = $ngopiResponse;
    $response->source = "webhook";
    echo json_encode($response);
}
else
{
    echo "Method not allowed";
}
?>

Please give me a solution for this case or maybe there are other alternative ways that I can do?

Thanks in advance.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

I dont understand where are you calling from. I can give you an alternative solution that may or may not work in your case (since I don’t fully understand your case):

This is your ajax-url on your site:

echo admin_url( 'admin-ajax.php' );

Usually we attach it to the JS to run AJAX calls:

wp_localize_script( 'THE_JS_THAT WAS_ENQUEUED', 'PARAMS', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );

Even without wp_localize_script you can always print the admin_url( ‘admin-ajax.php’ ) to screen, and input it in any other process.

Now that you have the AJAX link, you can use AJAX to get the current connected user, and return it, as long as you call it from the same browser (meaning same cookie).


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x