Wordpress Rest API returns error - wordpress

I'am developing a plugin for wordpress and have trouble with the Rest API.
On my test server it works without a problem. (v4.6.6)
On a different server (v4.4.10) the API returns this error message:
{"code":"rest_invalid_handler","message":"
Der Handler f\u00fcr die Route ist ung\u00fcltig","data":{"status":500}}%
The message is in german and means "The handler for the route is invalid." Don't understand why they translate the error messages for an API. Makes no sense for me. :)
The routes on the http://domain/wp-json are equal.
Maybe an problem with the different WP versions?
Definition of the route:
function __construct() {
add_action( 'rest_api_init', function(){
register_rest_route( 'test_namespace', 'ping', array(
'methods' => 'POST',
'callback' => array($this, 'ping_test'),
'permission_callback' => array($this, 'myhacks_permission_callback'),
) );
} );
}
Thanks for help.

I had the same issue. It seems that method ping_test cannot be private. If you change it to public, the error disappears.

Take a look at the WordPress core and you can see that the method passed as the callback aka ping_test must be callable.
So this error triggers only when that method doesn't exist (for example I just encountered it because of a typo) or if is not accessible(like a protected or private method)

Related

Wordpress REST Api: add_action( 'rest_api_init', callback) does not call the callback

Problem:
I'm trying to register a custom endpoint for a Wordpress plugin. The problem I face is that when I call the add_action('rest_api_init', callback), the callback function is not being called. In that callback function lives the "register_rest_route()" method, which in it's turn is not being called and I am unable to register any custom endpoints.
I'm using docker for development
No errors are being thrown
Code:
public function register()
{
$this->setup_init();
}
public function setup_init()
{
var_dump('print1');
add_action('rest_api_init', array($this, 'register_custom_endpoints'));
}
public function register_custom_endpoints()
{
var_dump('print2');
die();
register_rest_route('test', '/test', array(
'methods' => 'GET',
'callback' => 'menu_setup',
));
}
Question:
The code reaches the "var_dump('print1')", but the the "var_dump('print2')" is never reached. Am I missing something here?
After trying many options I found out that changing: "Setting -> permalinks -> common settings" to anything else then the option "Plain" solved the issue. The callback method is now being reached, and my custom endpoints are being registered.

Wordpress REST API cannot post comments

I am trying to post comments to my posts using the Wordpress JSON API but I keep getting an error.
Heres what I have done:
I have added the 'rest_allow_anonymous_comments' function
add_filter( 'rest_allow_anonymous_comments', '__return_true' );
Then went to the URL
https://example.com/wp-json/wp/v2/comments?post=192&author_email=mytestemail#gmail.com&author_name=TestName&content=ThisIsTestContent
But it just returns the error:
{"code":"rest_forbidden_param","message":"Query parameter not permitted: author_email","data":{"status":401}}
Does anyone know what I am doing wrong?
First of all, You have to create a endpoint for comment.
add_action('rest_api_init', function () {
register_rest_route( 'mycomment/v1', 'comment/(?P<post_id>\d+)',array(
'methods' => 'POST',
'callback' => 'post_comment'
));
});
Then the post_comment in callback will point it to another function to create another function for your logic. In this call back function, you can add your comment using wp_insert_comment().
function post_comment($request) {
// Your code here
}
Enjoy!

How do I write personalized endpoints in Wordpress?

I have personalized custom fields in Wordpress as well as additional things like "user_meta". I've even added some custom fields in the table to some post types.
Now I can call or write classic wordpress variables using wp-rest-api. But it cannot interfere with the private areas I add. There are different types of scenarios, prerequisites and different types that allow you to read / write to different fields, for example: "POST: https: //example.com/wp-json/wp/v2/posts? Title = .... & content = ... "function to add a new text.
Well my font was "fruits" though. Example: "POST: https: //example.com/wp-json/wp/v2/fruits? Title = .... & content = ...." How do I write a custom endpoint?
The simple and easy way to understand how to create a custom endpoint in WordPress rest api this website will be helpful: https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/
Below example will help you more to understand about the basic of custom end points:
GET: https: //example.com/wp-json/wp/v2/hello/world
Define Action:
add_action( 'rest_api_init', function(){
register_rest_route( 'wp/v2/hello', 'world', array(
'methods' => 'GET',
'callback' => 'rest_hello_world'
));
});
Call back function Definition:
function rest_hello_world(){
return "Hello World";
}
In order to create a POST method call simply change the method parameter as a POST:
register_rest_route( 'wp/v2/hello', 'world', array(
'methods' => 'POST',
'callback' => 'rest_hello_world'
));
Hope it will help you to understand the basic fundamental for creating custom endpoints!
Cheers
Jenil

Get current user inside register_rest_route method

How to retrive wp_get_current_user() inside a register_rest_route callback (Wordpress site)?
I'm just trying to do a simple hello wp_get_current_user()->user_login on a php test page:
add_action('rest_api_init', 'helloTest');
function helloTest() {
register_rest_route('hello', 'hello/(?P<id>\d+)', array(
'methods' => WP_REST_SERVER::READABLE,
'callback' => 'showHello'
));
}
function showHello($someVariable) {
echo "Hello " . wp_get_current_user()->user_login . $someVariable;
}
But wp_get_current_user() is null and wp_get_current_user->ID is 0;
I dont want to authenticate the user again. I just want to retrieve his username. If he is not logged in, just show empty an empty string.
If I have to authenticate again, how to add a "nonce" to it? On internet I just have examples using javascript, but not directly on PHP methods.
Issues in your code
First off, you should understand properly how to add custom WP REST API endpoints:
An endpoint's namespace (the first parameter passed to register_rest_route()) should be in this format: your-plugin/v<version>. E.g. hello/v1 or hello-world/v1 and not just hello or hello-world.
$someVariable (the first parameter passed to your endpoint callback function) is not just any variable — it's an instance of the WP_REST_Request class — and shouldn't be echo-ed like what you did here:
function showHello($someVariable) {
echo "Hello " . wp_get_current_user()->user_login . $someVariable;
}
And normally, the $someVariable is better be changed to $request (i.e. rename it to "request").
And you should return a valid WP REST API response. For example, to return just the username:
return new WP_REST_Response( wp_get_current_user()->user_login, 200 );
And know your own API endpoint URL..
(based on your original namespace)
/wp-json/hello/hello/1 <- correct
/wp-json/hello/?John <- incorrect
because in your code, the parameter is a number and not string: (?P<id>\d+)
I hope those help you, and once again, do read the handbook for a more detailed guide.
The Corrected Code
add_action( 'rest_api_init', 'helloTest' );
function helloTest() {
register_rest_route( 'hello/v1', 'hello/(?P<id>\d+)', array(
'methods' => WP_REST_SERVER::READABLE,
'callback' => 'showHello'
) );
}
function showHello( $request ) {
return new WP_REST_Response( wp_get_current_user()->user_login, 200 );
}
Now about getting the user (from the API endpoint — showHello())
If I have to authenticate again, how to add a "nonce" to it?
Just because the user is logged-in/authenticated to the (WordPress) site, it doesn't mean the user is automatically logged-in to the WP REST API. So yes, you'd need to either provide a nonce along with your API request, or use one of the authentication plugins mentioned right here.
Now in most cases, GET (i.e. read-only) requests to the API do not need any authentication, but if you'd like to retrieve the data of the currently logged-in user on your site, then one way is via the _wpnonce data parameter (either POST data or in the query for GET requests).
Example for a GET request:
http://example.com/wp-json/wp/v2/posts?_wpnonce=<nonce>
So based on your comment and the corrected code (above):
Theres no "code" that make the request. Its is just an anchor that
calls my route: Hello
You can add the nonce as part of the URL query string like so: (the namespace is hello/v1 and the <id> is 1)
// Make request to /wp-json/hello/v1/hello/<id>
$nonce = wp_create_nonce( 'wp_rest' );
echo 'Hello';
So try that out along with the corrected code and let me know how it goes. :)
And once again, be sure to read the REST API authentication handbook.

How to get current logged in user from WordPress via custom endpoints?

I have an endpoint in my WordPress plugin, and using it. I want to get the user who is currently logged in the WordPress. My endpoint looks like this:
add_action( 'rest_api_init', function () {
register_rest_route( 't2mchat/v2', '/get_curr_user', array(
'methods' => 'GET',
'callback' => 'get_curr_user'
));
});
The callback function:
function get_curr_user(WP_REST_Request $request){
$user = wp_get_current_user();
return $user;
}
This gives me back user ID as 0.
I read the article on WordPress official website about Authentication , and learned that I need to pass nonces, but since I am a new to this, I could not understand everything it says.
Also, I am calling this endpoint in my React app like this:
loadData() {
return fetch(`/wordpress/wp-json/t2mchat/v2/get_curr_user`)
.then(response => response.json())
.then(responseJson => {
this.setState({ curr_user: responseJson });
//console.log(this.state.curr_user, "curr user role");
})
.catch(error => {
console.error(error);
});
}
I am not sure how do I pass nonces in the request, so I can get the currently logged in user.
Can anyone with experience/idea suggest what changes I need to make in my code?
An example would be highly appreciated.
Thank you.
in your PHP file include the wp-load.php
include_once("wp-load.php");
then you can access to all native Wordpress Function just call them.
So you have to be able to retrieve the current logged in user by wp_get_current_user();
I used session storage to store user data when the wordpress initializes and retrieved from my endpoint. It worked for me.

Resources