Look at WordPress’s documentation on AJAX
In your theme or plugin, you’ll want to have code like:
add_action('wp_ajax_my_load_recent', 'my_load_recent_posts');
add_action('wp_ajax_nopriv_my_load_recent', 'my_load_recent_posts');
function my_load_recent_posts() {
$args = array(
/* Arguments go here, i.e. how many posts to get */
);
query_posts($args); /* [1] */
/* Header wrap output */
if (have_posts()) : while (have_posts()) : the_post(); /* [2] */
/* Output for each post */
endwhile; else :
/* Output for if there are no posts to get */
endif;
/* Footer wrap output */
wp_reset_query();
}
[1] query_posts()
documentation
[2] WordPress loop documentation
Then to reach this function you’ll want to have on your front end, assuming you’re using jQuery:
$.ajax(ajax_url/* [3] */, {
method: 'POST',
data: {
action: 'my_load_recent',
},
success: function(response) {
/* handling of the output returned by PHP function */
},
error: function() {
/* what to do if there's a server error, like 404
}
});
[3] See WordPress’s documentation on AJAX to generate the ajax_url
: “As this article suggests, use wp_localize_script() to make the URL available to your script, and generate it using this expression: admin_url(‘admin-ajax.php’)”