I display a random post loop on a page. I’d like to put a “refresh” link to refresh the content of the loop via ajax.
Is this possible?
This is my loop if it helps:
<ul id="content-inner" class="thumb-grid clearfix">
<?php query_posts('posts_per_page=20&orderby=rand'); ?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<li>
<a href="https://wordpress.stackexchange.com/questions/5155/<?php the_permalink(); ?>">
<img src="<?php echo $my_image_url = get('thumbnail'); ?>" alt="" />
<span class="title"><?php the_title(); ?></span>
<span class="feat"><?php $articletags = strip_tags(get_the_tag_list('',', ',''));echo $articletags;?></span>
</a>
</li>
<?php endwhile;?>
<?php endif; ?>
<?php wp_reset_query(); ?>
</ul>
Shouldn’t be too tricky. First: create a javascript file and add this:
jQuery(document).ready(function($){
$('#refresh-links-id').click(function(e){
e.preventDefault();
$.post(ajaxurl,{action:'jpb_random_loop'}, function(data){
$('#content-inner').fadeOut(250).empty().append( data ).fadeIn(250);
});
});
});
Save that file in your theme directory somewhere (could be in a subdirectory too). For this to work, the refresh link should not be inside ul#content-inner
. Pretty basic jQuery post call, though.
Next, add this to your theme’s functions.php
file:
function jpb_template_redirect(){
if( <conditions under which this javascript should execute> ){
wp_enqueue_script( 'random-loop', '<url to the javascript file above>', array( 'jquery' ), '1.0' );
}
}
function jpb_random_loop_cb(){
query_posts('posts_per_page=20&orderby=rand');
if (have_posts()) : while (have_posts()) : the_post(); ?>
<li>
<a href="https://wordpress.stackexchange.com/questions/5155/<?php the_permalink(); ?>">
<img src="<?php echo $my_image_url = get('thumbnail'); ?>" alt="" />
<span class="title"><?php the_title(); ?></span>
<span class="feat"><?php $articletags = strip_tags(get_the_tag_list('',', ',''));echo $articletags;?></span>
</a>
</li>
<?php endwhile; endif;
die();
}
add_action( 'template_redirect', 'jpb_template_redirect' );
add_action( 'wp_ajax_jpb_random_loop', 'jpb_random_loop_cb' );
add_action( 'wp_ajax_nopriv_jpb_random_loop', 'jpb_random_loop_cb' );
That will tie everything together. Just make sure the logic is correct in the template_redirect
function so that the javascript is included in the right pages.