add_action( 'rest_api_init', function () {
register_rest_route( 'vinay', '/ajax_blog/', array(
'methods' => 'GET',
'callback' => 'blog_ajax_function'
) );
});
Now, you can do your query inside a callback function:
// Now, you can do your query inside a callback function:
function blog_ajax_function(){
$recent_posts = wp_get_recent_posts( $args, OBJECT );
foreach ( $recent_posts as $post ) {
$data[]['title'] = get_the_title( $post->ID );
$data[]['date'] = get_the_date( 'Y-m-d H:i:s', $post->ID );
$data[]['permalink'] = get_the_permalink( $post->ID );
$data[]['thumbnail'] = get_the_post_thumbnail_url( $post->ID );
}
return $data;
}
Let's bind an action to page load and fill the page with fancy bubbly posts, just like spongebob did! This goes in your static website's HTML file ( Replace the code from your question by removing it and using this ) Don't forget to change example.com
to your domain!
<section id="blog"><div id="container-div"></div></section>
<script>
(function(){
$.ajax({
type: 'GET',
url: 'http://example.com/wp-json/vinay/ajax_blog',
dataType: 'json',
success: function (data) {
if (data != null) {
$.each(data, function(index, element) {
$('#container-div').append('<a href="'+element.permalink+'"><img src="'+element.thumbnail+'" alt="'+element.title+'"/><span>'+element.title+'</span>' +element.date+ '</a>');
});
}
}
});
})(jQuery);
</script>
This will automatically append a list of clickable recent posts to the <div id="container-div"></div>
that we create in our HTMl to contain the posts when the page loads.