Last active
August 3, 2019 00:34
-
-
Save amouratoglou/220ebf45752b1a1a5a27ed4e2dbeff5f to your computer and use it in GitHub Desktop.
Get AJAX posts in Wordpress #ajax #wordpress #javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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()) { | |
$ajaxposts->the_post(); | |
$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> | |
</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> | |
</div> | |
<div class="load-now" style="margin-top:100px;background:green;color:#fff;cursor:pointer;display:inline-block;width:auto; padding:10px;">LOAD POSTS</div> | |
<script> | |
// Ajax load posts on click | |
function loadPosts(){ | |
jQuery.ajax({ | |
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(this).css('opacity','0.6'), | |
jQuery( '.loading' ).show('slow'), | |
loadPosts(); | |
}); | |
</script> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment