Sunday, December 20th, 2020
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);
})
Tags: Ajax, Custom, Endpoint, PHP, Route, WordPress
Posted in WordPress | No Comments »