1

I have a WordPress website and I want to add a custom endpoint that sends the metadata of the users.

Important: The already API works only by calling it like this "domain-name.com/?rest_route=/wp/v2/users/". I know that for the API to work properly the standard solution for a custom endpoint is to change the permalink settings from plain to post.

Is there any solution without changing that setting?

The standard pre-built endpoints work fine when I call them like in the above example.

For example this code only works for the wordpress websites with the permalink settings as post. Calling the api like this (domain.com/wp-json/wp/v2/custom-ep. If I place the same code in the other website with permalink setting and call it as mentioned above ("domain-name.com/?rest_route=/wp/v2/users/"), I will get error 404. enter image description here

code:

function create_custom_endpoint()
{
    register_rest_route(
        'wp/v2', // Namespace
        '/custom-ep', // Route
        array(
            'methods' => 'GET', // HTTP method
            'callback' => 'get_response', // Callback function
        )
    );
}

function get_response()
{
    // This is your custom response data
    return 'This is your data!';
}

// Hook the custom endpoint registration to rest_api_init
add_action('rest_api_init', 'create_custom_endpoint');
5
  • why do you want to set pretty url when everything works without ? Commented Aug 3, 2024 at 21:10
  • @mmm I want my custom endpoint like this "domain-name.com/?rest_route=/wp/v2/custom-endpoint/" to work. Commented Aug 3, 2024 at 22:22
  • why this custom endpoint doesn't work ? edit your question to show the debug you made. why do you speak about permalink settings in your question ? Commented Aug 3, 2024 at 22:55
  • @mmm this is what I am trying to figure out. I've updated the question. Commented Aug 4, 2024 at 14:35
  • this is strange, I tried your code and it works for me on url .../wp-json/wp/v2/custom-ep and .../?rest_route=/wp/v2/custom-ep. look in .htaccess if there is something weird. Commented Aug 4, 2024 at 14:51

1 Answer 1

0

I was adding the script/snippet in the wrong functions.php file (wrong theme). I added the code in the correct functions.php and it worked.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.