phpwordpress-rest-apiwordpress-plugin-creation

How to make Wordpress REST API custom endpoint public?


I'd like to make a custom endpoint via plugin but it's not working for the anonymous user. How do you make it publicly accessible? If that's not possible then how do you login via command line?

I've followed this example. Added the code below to the "hello.php" plugin.

function prefix_get_endpoint_phrase() {
    return rest_ensure_response('Hello World, this is the WordPress REST API');
}
function prefix_register_example_routes() {
    register_rest_route('hello-world/v1', '/phrase', [
        'methods'  => WP_REST_Server::READABLE,
        'callback' => 'prefix_get_endpoint_phrase',
        'permission_callback' => '__return_true',
    ]);
}
add_action('rest_api_init','prefix_register_example_routes');

I enter https://example.com/wordpress/wp-json/hello-world/v1/phrase and it works fine for a logged-in user. Anonymous user gets 401 REST API disabled. However, https://example.com/wordpress/wp-json works just fine for the anonymous. I'm testing it on a clean Wordpress 6.2.2 installation (permalinks have been set to post name).

Also tried accessing it via command line. I've followed these instructions (created application password, used curl template):

curl --user "username:xxxx xxxx xxxx xxxx xxxx xxxx" https://example.com/wordpress/wp-json/hello-world/v1/phrase

The result is 403 Forbidden.


Solution

  • It turned out it was a hosting issue.

    EDIT: I went to DirectAdmin. Clicked on Ochrona stron www (WAF). Selected option Niski and then pressed button Ustaw.