سؤال

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="<?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="<?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.

نصائح أخرى

This plugin seems like it would do what you are looking for.

http://wordpress.org/extend/plugins/wp-ajax-random-posts/

If you don't want to use the plugin you could always check out the code for the refresh link and try to get it to work for you.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى wordpress.stackexchange
scroll top