在wordpress中使用Ajax“加载更多帖子”

时间:2012-10-01 12:44:58

标签: ajax wordpress pagination

我正在尝试在Blog Page上创建ajax分页。 我需要做的是最初显示5个帖子,然后在点击“加载更多帖子”链接时再加载5个帖子。

以下是我正在使用的javascript:

<script>
    jQuery(document).ready(function() {
        // ajax pagination
        jQuery('.nextPage a').live('click', function() { 

            // if not using wp_pagination, change this to correct ID
            var link = jQuery(this).attr('href');

            // #main is the ID of the outer div wrapping your posts
            jQuery('.blogPostsWrapper').html('<div><h2>Loading...</h2></div>');

            // #entries is the ID of the inner div wrapping your posts
            jQuery('.blogPostsWrapper').load(link+' .post')
        });
    }); // end ready function
</script>

问题是,当我点击链接时,旧帖子会被新帖子取代,我需要显示旧帖子以及新帖子......

这是更新的jQuery代码,它启用了ajax分页。

jQuery(document).ready(function(){
jQuery('.nextPage a').live('click', function(e){
  e.preventDefault();
  var link = jQuery(this).attr('href');
  jQuery('.blogPostsWrapper').html('Loading...');
  jQuery('.blogPostsWrapper').load(link+' .post');
  });
  });

现在唯一的问题是旧帖子被删除,我需要保留旧帖和新帖..

3 个答案:

答案 0 :(得分:1)

以下是我使用的最终代码,现在一切正常......

// Ajax Pagination
jQuery(document).ready(function($){
    $('.nextPage a').live('click', function(e)  {
    e.preventDefault();
    $('.blogPostsWrapper').append("<div class=\"loader\">&nbsp;</div>");

    var link = jQuery(this).attr('href');

    var $content = '.blogPostsWrapper';
    var $nav_wrap = '.blogPaging';
    var $anchor = '.blogPaging .nextPage a';
    var $next_href = $($anchor).attr('href'); // Get URL for the next set of posts

    $.get(link+'', function(data){
    var $timestamp = new Date().getTime();
    var $new_content = $($content, data).wrapInner('').html(); // Grab just the content
    $('.blogPostsWrapper .loader').remove();
    $next_href = $($anchor, data).attr('href'); // Get the new href
    $($nav_wrap).before($new_content); // Append the new content
    $('#rtz-' + $timestamp).hide().fadeIn('slow'); // Animate load
    $('.netxPage a').attr('href', $next_href); // Change the next URL
    $('.blogPostsWrapper .blogPaging:last').remove(); // Remove the original navigation
    });

    });
}); // end ready function

答案 1 :(得分:0)

您可以尝试以下代码吗?这就是我在自己的网站上工作的方式。

取代:

jQuery('.blogPostsWrapper').load(link+' .post')

使用:

$.get(link+' .post', function(data){
$('.blogPostsWrapper').append(data);
});

答案 2 :(得分:0)

您应该使用jQuery append()添加新帖子而不使用旧帖子。

jQuery load()将替换元素中的数据。引自jQuery API:

  

.load()将匹配元素的HTML内容设置为返回的   数据。这意味着该方法的大多数用途都非常简单:

相关问题