By Sahas Katta


2011-02-13 01:52:55 8 Comments

I have a list of the most recent post titles in sidebar.php. Here is an example of how that code looks:

<?php $args = array('posts_per_page' => 20); ?>
<?php $sidebar = new WP_Query($args); ?>
<?php if ( $sidebar->have_posts() ) : ?>
<?php while ( $sidebar->have_posts() ) : $sidebar->the_post(); ?>

<div class="story">
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">
  <?php the_title(); ?> - <?php the_time("F j, Y h:i A"); ?>
</a>
</div>

<?php endwhile; ?>
<?php endif; ?>

That part works perfectly. It displays the 20 latest post titles and post times wrapped in permalinks. However, I am trying to do a bit more. I want to create a load more button at the bottom to fetch the next 20 post titles. I know my jQuery and that is not the issue.

I need help with figuring out how to create a custom loop in a new custom .php template file that only generates the html above. That file needs to be able to accept a parameter for a page number, so that my javascript can fetch an incremented URL each time.

I would appreciate any help, thanks!

1 comments

@Bainternet 2011-02-13 13:36:02

you can wrap your function and hook it to ajax call like this:

//if you want only logged in users to access this function use this hook
add_action('wp_ajax_more_links', 'my_AJAX_more_links_function');
//if you want none logged in users to access this function use this hook
add_action('wp_ajax_nopriv_more_links', 'my_AJAX_more_links_function');

function my_AJAX_more_links_function(){
    check_ajax_referer('more_links');
    $success_response = new WP_Ajax_Response();
    $args = array('posts_per_page' => 20 , 'offset' => $_POST['offset']);
    $sidebar = new WP_Query($args);
    if ( $sidebar->have_posts() ){ 
         while ( $sidebar->have_posts() ) {
            $sidebar->the_post(); 
            $out .= '<div class="story">';
            $out .= '<a href="' . the_permalink().'" title="'. the_title'.">' . the_title().' - '.the_time("F j, Y h:i A") .'</a></div>';
        }
        $success_response->add(array(
                    'what' => 'has',
                    'data' => array('html' => $out, 'offset' => $_POST['offset']
        ));
    }else{
        $out = __('Sorry but No more!');
        $success_response->add(array(
                    'what' => 'none',
                    'data' => $out
                ));
    }

    $success_response->send();      
    exit;   
}

then add this to your sidebar function at the end

<span class="more_links"></span>
<span class="get_more">
    <input type="hidden" name="offset" id="offset" value="20">
    <input type="submit" name="more" id="more" value="Get more links">
</span>
<script type="text/javascript" >
jQuery(document).ready(function($) {
    jQuery('#more').click(function() { 
        var data = {
            action: 'more_links',
            offset: jQuery( '#offset' ).val(),
            _ajax_nonce: <?php echo wp_create_nonce( 'more_links' ); ?>
        };

        // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
        jQuery.post(ajaxurl, data, function(response) {
            var res = wpAjax.parseAjaxResponse(response, 'ajax-response');
            jQuery.each( res.responses, function() { 
                if (this.what == 'has') {
                    //insert links
                    jQuery(".more_links").append( this.data.html ); 
                    //update offset value
                    jQuery("#offset").val(this.data.offset);
                    jQuery(".more_links").fadeIn("fast");
                }else{
                    //no more links found
                    jQuery(".more_links").append( this.data.html );
                    jQuery(".get_more").remove();

                }
                //end if
                });//end each


        });

        return false;
    })
});
</script>

and there you go, oh wait you need to add wp-ajax-response so

add_action('wp_head','add_scripts_121');
function add_scripts_121(){
    wp_enqueue_script('wp-ajax-response');
}

and you are set

@AlxVallejo 2012-10-24 17:35:04

This answer is a goldmine that you really can't find in textbooks

@Bram Vanroy 2015-02-27 11:03:05

I know that this is an old answer, but it's still relevant to me. I do wonder why the return false is necessary, as you are calling it on the click event of a button, to which there's no form related. I think you could leave it out. Also, how does check_ajax_referer know what to check, as you are not using any nonce fields? And what is wp-ajax-response?

Related Questions

Sponsored Content

0 Answered Questions

How to include files in the loop via ajax

1 Answered Questions

1 Answered Questions

[SOLVED] Nested loop : wich way/order?

  • 2017-01-08 12:11:54
  • Cha
  • 40 View
  • 1 Score
  • 1 Answer
  • Tags:   query php

0 Answered Questions

Fetch loop of custom post types with AJAX

1 Answered Questions

[SOLVED] Autocomplete for titles via ajax - rework of past post away from like_escape()

  • 2015-11-09 16:10:35
  • Work-Together2013
  • 168 View
  • 0 Score
  • 1 Answer
  • Tags:   jquery ajax

1 Answered Questions

[SOLVED] Fetch and show multiple custom fields via AJAX

  • 2015-07-07 16:58:20
  • Robert hue
  • 1355 View
  • 3 Score
  • 1 Answer
  • Tags:   custom-field ajax

1 Answered Questions

[SOLVED] setup_postdata in "loop-handling" php file called via $.ajax

  • 2014-04-30 13:25:01
  • Matthias Max
  • 646 View
  • 0 Score
  • 1 Answer
  • Tags:   loop ajax

1 Answered Questions

[SOLVED] Ajax loop in sidebar to load post titles/categories

  • 2013-04-01 02:02:49
  • andy
  • 1566 View
  • 1 Score
  • 1 Answer
  • Tags:   loop ajax

2 Answered Questions

[SOLVED] Loading pages via Ajax and displaying titles

  • 2011-09-07 19:13:55
  • Daniel Sachs
  • 1832 View
  • 0 Score
  • 2 Answer
  • Tags:   ajax title

1 Answered Questions

[SOLVED] Getting selection of posts based on loop variables via Ajax

  • 2012-07-11 08:17:57
  • Squrler
  • 533 View
  • 0 Score
  • 1 Answer
  • Tags:   loop ajax

Sponsored Content