Simple WordPress AJAX Pagination

I use loop + jQuery below to load in the next set of pages, and it works on the first click, but when the next page loads and I click "new posts", it reloads the whole page, Any ideas?

<div id="content">
    <?php
$new_query = new WP_Query();
$new_query->query('post_type=post&showposts=1'.'&paged='.$paged);
?>

<?php while ($new_query->have_posts()) : $new_query->the_post(); ?>
<?php the_title(); ?>

<?php endwhile; ?>
    <div id="pagination">
    <?php next_posts_link('&laquo; Older Entries', $new_query->max_num_pages) ?>
    <?php previous_posts_link('Newer Entries &raquo;') ?>
    </div>
</div><!-- #content -->

<script>
$('#pagination a').on('click', function(event){
event.preventDefault();
var link = $(this).attr('href'); //Get the href attribute
$('#content').fadeOut(500, function(){ });//fade out the content area
$('#content').load(link + ' #content', function() { });
$('#content').fadeIn(500, function(){ });//fade in the content area

});
</script>
+5
source share
2 answers

You use the jQuery method load()to insert content, which is a shortcut to $.ajax, which of course dynamically inserts the content.

Dynamic content requires event delegation to a non-dynamic parent, something jQuery simplifies with on()

jQuery(function($) {
    $('#content').on('click', '#pagination a', function(e){
        e.preventDefault();
        var link = $(this).attr('href');
        $('#content').fadeOut(500, function(){
            $(this).load(link + ' #content', function() {
                $(this).fadeIn(500);
            });
        });
    });
});
+19
source

I used adeneo solution with a few minor changes.

  • , , . , Ajax, .
  • , . Ajax, clicked , , .disabled.
  • , , fadeOut/In ( display: none; ). , .

:

$('#content').on('click', '#pagination :not(.disabled) a', function(e){
    e.preventDefault();
    var link = $(this).attr('href');
    $.post( link, function( data ) {
        var content = $(data).filter('#content');
        var pagination = $(data).filter('#pagination');
        $('#pagination').html(pagination.html());
        $('#content').animate(
            {opacity: 0},
            500, 
            function(){
                $(this).html(content.html()).animate(
                    {opacity: 1},
                    500
                );
            }
        );
    });
});
+3

All Articles