For Creating custom api in wordpress we need to register a new route url for our custom rest api.
Go the theme functions.php file and add the code
add_action('rest_api_init', function() {
register_rest_route('twentyone_wl/v1', 'posts', [
'methods' => 'GET',
'callback' => 'twentyone_wl_posts',
]);
});
/*'twentyone_wl/v1' is namespace define*/
Now add the function which gives some data when you hit the custom api url
function twentyone_wl_posts() {
$args = [
'numberposts' => 99999,
'post_type' => 'post'
];
$posts = get_posts($args);
$data = [];
$i = 0;
foreach($posts as $post) {
$data[$i]['id'] = $post->ID;
$data[$i]['title'] = $post->post_title;
$data[$i]['content'] = $post->post_content;
$data[$i]['slug'] = $post->post_name;
$data[$i]['featured_image']['thumbnail'] = get_the_post_thumbnail_url($post->ID, 'thumbnail');
$data[$i]['featured_image']['medium'] = get_the_post_thumbnail_url($post->ID, 'medium');
$data[$i]['featured_image']['large'] = get_the_post_thumbnail_url($post->ID, 'large');
$i++;
}
return $data;
}
Now hit the url in browser for Ex: http://localhost/demowordpress/wp-json/twentyone_wl/v1/posts
Now You see this type JSON data for your custom api
Thanks for visting and comment below if it is useful for You!!!!