How to get current logged in user using Wordpress Rest Api?

后端 未结 5 1938
盖世英雄少女心
盖世英雄少女心 2020-12-25 11:32

I tried to add a custom request.

add_action(\'rest_api_init\', function () {
    register_rest_route( \'custom\', \'/login\', array(
        \'methods\' =>         


        
5条回答
  •  天命终不由人
    2020-12-25 12:02

    I spent two days searching for a simple way without adding plugins.

    first in function.php where you define your api

    //enqueue the script which will use the api
    function api_callings_scripts() {
        wp_enqueue_script('score-script', get_template_directory_uri() . '/js/ScoreSaving.js', ['jquery'], NULL, TRUE);
        // Pass nonce to JS.
        wp_localize_script('score-script', 'ScoreSettings', [
          'nonce' => wp_create_nonce('wp_rest'),
        ]);
    }
    add_action( 'wp_enqueue_scripts', 'api_callings_scripts' ); 
    

    Then your script Ajax call cloud be something like this

    jQuery.ajax({
          type: "POST",
          url: "/wp-json/score/update",
          data: {"var1":"value1"},
          beforeSend: function(xhr) {
            xhr.setRequestHeader('X-WP-Nonce', ScoreSettings.nonce);
          },
        success: 
            function( data ) {
              console.log( data );
            }
        });
    

    Now you can use get_current_user_id() inside your API code.

提交回复
热议问题