Search code examples
wordpressrestwordpress-rest-api

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?


Solution

  • 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