CodeHQ

Creating a custom route / endpoint in WordPress

The PHP

add_action(
	'rest_api_init',
	function () {
  		register_rest_route(
  			'myname/v1',
  			'/thethingimgetting',
  			array(
				'methods' => 'GET',
				'callback' => 'thefunctionwiththeloop',
			)
		);
	}
);
function thefunctionwiththeloop() {
	$args = array(
		'post_type' 	=> 'posts',
		'numberposts'   => -1,
	);
	$query = new WP_Query($args);
	$myPosts = array();
	if ($query->have_posts()) {
		foreach ($query->posts as $post) {
			$myPosts[] = $post;
		}
	}
	return rest_ensure_response($myPosts);
}

The JS

var api_url = '/wp-json/myname/v1/thethingimgetting';
$.ajax({
	url: api_url,
	method: 'GET'
})
.done(function(response){
	console.log(response);
})