Create a JSON Endpoint in WordPress

If you’re a WordPress developer, sooner or later you’re going to need to create a JSON endpoint. Fortunately, WordPress makes it relatively easy to do so. In this blog post, we’ll show you how to create a JSON endpoint in WordPress.

The first thing you need to do is create a plugin. To do that, simply create a new folder in your WordPress installation’s wp-content/plugins directory. For this example, we’ll call the folder custom_rest. Inside that folder, create a new file called custom_rest.php. The contents of that file should be as follows: 

The contents of that file should be as follows: 

add_action('rest_api_init', function () {
  register_rest_route( 'custom-rest/v1', 'posts', [
            'methods'  => 'GET',
            'callback' => 'custom_rest_posts_by_types',
            'permission_callback' => function() {
		          return true;
		      }
  ]);
register_rest_route( 'custom-rest/v1', 'post/id/(?P<id>\d+)', [
            'methods'  => 'GET',
            'callback' => 'custom_rest_posts_by_id',
            'args' => [
		      'id' => [
		        'validate_callback' => function($param, $request, $key) {
		          return is_numeric( $param );
		        }
		      ],
		    ],
  ]);

});

function custom_rest_posts_by_types($request){
	$types = ['type_a', 'type_b', 'type_c'];

	global $wpdb;
	$result = [];

	foreach ($types as $type) {
		//get post by type
		$posts_by_type =  $wpdb->get_results("SELECT DISTINCT pm.post_id FROM {$wpdb->prefix}postmeta as pm WHERE pm.meta_key LIKE 'component_type' AND lower(pm.meta_value) LIKE '%".strtolower($type)."%'");
		$post_ids = [];
		foreach ($posts_by_type as $key => $p) {
			$result[$p->post_id] = [
				'id' => $p->post_id,
			];
		}

		
	}
	return new WP_REST_Response($result, 200);

}

function custom_rest_posts_by_id($request){
	$id = $request['id'];
	$post = get_post($id);
	return new WP_REST_Response([$post], 200);
}

Then any app can access this endpoint at http://example.com/wp-json/custom-rest/v1/posts and http://example.com/wp-json/custom-rest/v1/post/id/[id]

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close