Search code examples
wordpresswordpress-rest-api

How can I create custom endpoint with post and get methods on wordpress api


I'm trying to make a custom endpoint, for example: https://localhostname.com/wp-json/company_name/settings

Where I'll keep some settings like theme colors and other things, but it seems there are many ways to do that and I just want the simplest way. All the searching on the web is making me really confused. So basically I want to make a POST request to the above URL like this:

{
  "primary_color": "0xFFFFFFFF",
  "secondary_color": "0xFFFFFF11"
}

and then get these same parameters in a GET request.

It's just that. No verification at all. Sorry if it's that simple, but I'm really having a hard time with this problem as I am not used to program with php at all.


Solution

  • To create a custom endpoint you will need to add below snippet to your function file:

    add_action( 'init', 'setup_init' );
    
    
    function setup_init() {
    
       add_action( 'rest_api_init', 'custom_endpoint' );
    
       function custom_endpoint() {
    
        register_rest_route( 'company_name', '/settings', array(
            'methods' => 'GET',
            'callback' => 'custom_callback',
        ));
    }
    
       function custom_callback($request_data){
           return 'hello world';
       }
    }
    

    Let me know if any query and do accept the answer if it works :)