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

wordpress.stackexchange https://wordpress.stackexchange.com/questions/370115

  •  20-04-2021
  •  | 
  •  

質問

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.

役に立ちましたか?

解決

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).

ライセンス: CC-BY-SA帰属
所属していません wordpress.stackexchange
scroll top