Wordpress

Register Custom Rest API

9 August 2021

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!!!!

Leave a Reply

Your email address will not be published. Required fields are marked *

five × four =

Author

Hello, I'm
Rajat Meshram

I am a WordPress Developer having 5+ years of Experience. My professional experience includes designing and implementing web pages, user interfaces and plugins for WordPress, helping clients to troubleshoot and fix their WordPress products, designing themes that are as functional as they are beautiful and working with a team of colleagues to create the best products possible.

Latest Post

Latest Tags