Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Get AJAX posts in Wordpress #ajax #wordpress #javascript
// the function returns HTML directly using a custom template
// add this to your functions.php or create a plugin
function get_ajax_posts()
// Query Arguments
$args = array(
'post_type' => 'post',
'posts_per_page' => '5',
'category_name' => 'noticias-institucionales',
'order' => 'DESC',
// The Query
$ajaxposts = new WP_Query($args);
$response = '';
// The Query
if ($ajaxposts->have_posts()) {
while ($ajaxposts->have_posts()) {
$response .= get_template_part('ajax_posts');
} else {
$response .= get_template_part('none');
echo $response;
exit; // leave ajax call
// Fire AJAX action for both logged in and non-logged in users
add_action('wp_ajax_get_ajax_posts', 'get_ajax_posts');
add_action('wp_ajax_nopriv_get_ajax_posts', 'get_ajax_posts');
// create a ajax-posts.php file with the template for each item
// called from line 25
<div class="item">
<h1><?php the_title();?></h1>
<div><?php the_content();?></div>
// use this on your template files
<div class="container_ajax" style="display:inline-block;width:100%;margin-top:100;x;">
<img class="loading" style="display:none;" src="loading.gif">
<div class="posts-area">
<div class="load-now" style="margin-top:100px;background:green;color:#fff;cursor:pointer;display:inline-block;width:auto; padding:10px;">LOAD POSTS</div>
// Ajax load posts on click
function loadPosts(){
type: 'POST',
url: '<?php echo admin_url('admin-ajax.php');?>',
dataType: "html", // add data type
data: { action : 'get_ajax_posts' },
success: function( response ) {
console.log( response );
jQuery( '.loading' ).hide('slow'),
jQuery( '.posts-area' ).html( response );
jQuery( ".load-now" ).click(function() {
jQuery(this).css('transition','all 0.3s ease-in-out'),
jQuery( '.loading' ).show('slow'),
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment