Create a custom route in WordPress rest API – Updated 2021

Create a custom route in WordPress rest API – Updated 2021



Today we are going to create a custom route for WordPress rest API. For this, we need to add code in our theme, More specifically in functions.php





First we create function where we define route



//Here we are calling callback function, Note this function called in hook   

    function get_all_forum_posts()
    {
        // here WP_REST_SERVER::READABLE adds GET dynamically

        register_rest_route('custom/v1','topics', array(
            'methods'  => WP_REST_SERVER::READABLE,
            'callback' => 'customTopics'
        ));
    }

In the above code, we are setting route “custom/v1/topics”.





Note in above code we defining



“custom/v1” and “topics”





as First and Second argument in function “get_all_forum_posts”

Now we need to call our function, For this, we are going to use WordPress Hook “rest_api_init”.



    // here we have a wordpress hook where we are calling function

    add_action('rest_api_init', 'get_all_forum_posts');

In the callback we are calling a function above “‘callback’ => ‘customTopics'”, So here we have to create “customTopics” function that we need to create.





    
    // this function will return output

    public function customTopics()
    {
        $postArray = [];        

        $posts = new WP_Query(array(
           'post_type' => 'post'
        ));

        while($posts->have_posts())
        {
            array_push($postArray, get_the_title());
        }
        
        // for converting to json array use json_encode($postArray)
        return $postArray;

    }
    

Now navigate to url like this




http://yourSite/wp-json/custom/v1/topics

http://localhost/wp-json/custom/v1/topics

This should return





// Posts array should be returned when you visit the url using api route



%d bloggers like this: