AJAX在分类页面中加载更多帖子

时间:2013-05-29 作者:Ranjan Agarwal

我正在开发一个主题,我需要用ajax加载更多帖子。目前,当我在分类页面上单击“加载更多”时,所有帖子都在加载。类别。php如下所示:`

>> 设计<<

    <?php $counter = 0; ?>
              <?php while ( have_posts() ) : the_post(); ?>
              <?php  $style = ($counter % 2 == 0) ? \'col1 masonry-item \' :  \'col2 masonry-item \'; ?>
              <article id="post-<?php the_ID(); ?>" class="single-article post <?php echo $style; ?>" >
                  <div class="flip">
                    <a href="<?php the_permalink() ?>" rel="bookmark">
                      <?php if (has_post_thumbnail( $post->ID) ) { ?>
                       <?php if ($counter % 2 == 0) {
                        $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), \'masonry_thumb_large\');
                       } else {
                        $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), \'masonry_thumb_small\');
                       } ?>
                      <img src="<?php echo $image[0]; ?>" alt="" />
                      <?php } ?>
                    </a>          
                  </div>
                  <div class="post-meta click">
                    <a href="<?php echo the_permalink() ?>" rel="bookmark">
                      <div class="grid-text">
                        <h2 class="masonry-cat"><?php echo the_category(\'/ \') ?> &#124; N&#186; <?php the_field(\'sub_page_article_number\'); ?> </h2>
                        <h2><?php echo get_the_title(); ?></h2>
                              <?php the_excerpt(); ?>
                              <a href="<?php echo the_permalink() ?>" class="click-more">More</a>
                      </div>
                    </a>
                  </div>
              </article>

                  <?php $counter++; endwhile;?>

    </div> <!-- end of postslist -->
    <a class="load_more" data-nonce="<?php echo wp_create_nonce(\'load_posts\') ?>" href="javascript:;"><span>&#43;</span> Load More <span>&#43;</span></a>
</div>`
单击“加载更多”按钮后,将调用/功能。包含以下代码的php:

add_action( "wp_ajax_load_more", "load_more_func" );
function load_more_func() {
if ( !wp_verify_nonce( $_REQUEST[\'nonce\'], "load_posts" ) ) {
  exit("No naughty business please");
}
$offset = isset($_REQUEST[\'offset\'])?intval($_REQUEST[\'offset\']):0;
$posts_per_page = isset($_REQUEST[\'posts_per_page\'])?intval($_REQUEST[\'posts_per_page\']):10;
$post_type = isset($_REQUEST[\'post_type\'])?$_REQUEST[\'post_type\']:\'post\';
ob_start(); 


$args = array(
      \'post_type\'=>$post_type,
    \'offset\' => $offset,
    \'posts_per_page\' => $posts_per_page,
    \'orderby\' => \'date\',
    \'order\' => \'DESC\'
      );
$posts_query = new WP_Query( $args );
if ($posts_query->have_posts()) {
  $result[\'have_posts\'] = true; 
  $counter = 0;
  while ( $posts_query->have_posts() ) : $posts_query->the_post(); ?>

  <?php  $style = ($counter % 2 == 0) ? \'col1 masonry-item \' :  \'col2 masonry-item \'; ?>
  <article id="post-<?php the_ID(); ?>" class="single-article post masonry-brick <?php echo $style; ?>" >
    <div class="flip">
      <a href="<?php the_permalink() ?>" rel="bookmark">
        <?php if (has_post_thumbnail( $post->ID) ) { ?>
          <?php if ($counter % 2 == 0) {
          $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), \'masonry_thumb_large\');
          } else {
          $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), \'masonry_thumb_small\');
          } ?>
        <img src="<?php echo $image[0]; ?>" alt="" />
        <?php } ?>
      </a>          
    </div>
    <div class="post-meta click">
      <a href="<?php echo the_permalink() ?>" rel="bookmark">
        <div class="grid-text">
          <h2 class="masonry-cat"><?php echo the_category(\'/ \') ?> &#124; N&#186; <?php the_field(\'sub_page_article_number\'); ?> </h2>
          <h2><?php echo get_the_title(); ?></h2>
            <?php the_excerpt(); ?>
            <a href="<?php echo the_permalink() ?>" class="click-more">More</a>
        </div>
      </a>
    </div>
</article>

  <?php $counter++; endwhile;
$result[\'html\'] = ob_get_clean();

else {
$result[\'have_posts\'] = false;


if(!empty($_SERVER[\'HTTP_X_REQUESTED_WITH\']) && strtolower($_SERVER[\'HTTP_X_REQUESTED_WITH\']) == \'xmlhttprequest\') {
        $result = json_encode($result);
        echo $result; 
    }
else { 
        header("Location: ".$_SERVER["HTTP_REFERER"]);
    }
die();
}

javascript是:

$(\'.load_more:not(.loading)\').live(\'click\',function(e){
e.preventDefault();
var $load_more_btn = $(this);
var post_type = \'post\'; 
var offset = $(\'#posts_list .single-article\').length;
var nonce = $load_more_btn.attr(\'data-nonce\');
$.ajax({
    type : "post",
    context: this,
    dataType : "json",
    url : headJS.ajaxurl,
data : {action: "load_more", offset:offset, nonce:nonce, post_type:post_type, posts_per_page:headJS.posts_per_page},
    beforeSend: function(data) {
        $load_more_btn.addClass(\'loading\').html(\'+ Loading... +\');
        },
        success: function(response) {
                if (response[\'have_posts\'] == 1){
                    var $newElems = $(response[\'html\'].replace(/(\\r\\n|\\n|\\r)/gm, \'\')).css({ opacity: 0 });
                    $newElems.imagesLoaded(function(){
                            $newElems.animate({ opacity: 1 });
                            $(\'#posts_list\').append( $newElems ).masonry( \'appended\', $newElems); 
                            $load_more_btn.removeClass(\'loading\').html(\'+ Load More +\');
                        });
                    } else {
                        $load_more_btn.removeClass(\'loading\').addClass(\'end_of_posts\').html(\'<span>End of posts</span>\'); 
                    }
                }
    });
我尝试过以不同的方式查询帖子,但没有任何效果。任何帮助都将不胜感激。

1 个回复
最合适的回答,由SO网友:Milo 整理而成

您的查询参数不包含任何category arguments. 你需要通过并设置catcategory_name 以及每页的帖子类型、偏移量和帖子。您可以通过以下方式获取当前类别的IDget_queried_object():

$queried_object = get_queried_object();  
$cat_id = $queried_object->term_id;
输出并检索类别模板中的某个位置的值,或者更好,当您enqueue your ajax javascript, 检查是否is_category 和使用wp_localize_script() 将该数据传递到脚本。

结束

相关推荐

Get_Posts()不考虑用户权限

我想在我的wp上显示登录用户帖子的链接列表。所以我开始这样做:$posts_array = get_posts( array( \'post_type\' => \'download\', \'post_status\' => \'publish\' ) ); //$posts_array = apply_filters( \'downloads_shortcode\', $posts_array ); foreach($posts_array as $post) {