WP_Query and next_posts_link

时间:2011-06-19 作者:Tom

我不知道如何使next\\u posts\\u link()在自定义WP\\u查询中工作。功能如下:

function artists() {
  echo \'<div id="artists">\';
  $args = array( \'post_type\' => \'artist\', \'posts_per_page\' => 3, \'paged\' => get_query_var( \'page\' ));
  $loop = new WP_Query( $args );
  while ( $loop->have_posts() ) : $loop->the_post();
    echo \'<a class="artist" href="\'.get_post_permalink().\'">\';
    echo \'<h3 class="artist-name">\'.get_the_title().\'</h3>\';
    $attachments = attachments_get_attachments();
    $total_attachments = count( $attachments );
    for( $i=0; $i<$total_attachments; $i++ ) {
      $thumb = wp_get_attachment_image_src( $attachments[$i][\'id\'], \'thumbnail\' );
      echo \'<span class="thumb"><img src="\'.$thumb[0].\'" /></span>\';
    }
    echo \'</a>\';
  endwhile;
  echo \'</div>\';
  next_posts_link();
}
有人能告诉我我做错了什么吗?

谢谢

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

尝试向函数传递max\\u num\\u页:

next_posts_link(\'Older Entries »\', $loop->max_num_pages);

SO网友:Bainternet

next_posts_linkprevious_posts_link , 与其他几个函数一样,使用一个名为$wp_query. 此变量实际上是WP\\u查询对象的一个实例。然而,当您创建我们自己的WP\\u查询实例化时,您没有这个全局变量$wp_query, 这就是分页无法工作的原因。

为了解决这个问题,你耍了个花招$wp_query 全球的

//save old query
$temp = $wp_query; 
//clear $wp_query; 
$wp_query= null; 
//create a new instance
$wp_query = new WP_Query();
$args = array( \'post_type\' => \'artist\', \'posts_per_page\' => 3, \'paged\' => get_query_var( \'page\' ));
$wp_query->query($args);
while ( $wp_query->have_posts() ) : $wp_query->the_post();
    echo \'<a class="artist" href="\'.get_post_permalink().\'">\';
    echo \'<h3 class="artist-name">\'.get_the_title().\'</h3>\';
    $attachments = attachments_get_attachments();
    $total_attachments = count( $attachments );
    for( $i=0; $i<$total_attachments; $i++ ) {
      $thumb = wp_get_attachment_image_src( $attachments[$i][\'id\'], \'thumbnail\' );
      echo \'<span class="thumb"><img src="\'.$thumb[0].\'" /></span>\';
    }
    echo \'</a>\';
  endwhile;
  echo \'</div>\';
  next_posts_link();
//clear again
$wp_query = null; 
//reset
$wp_query = $temp;

结束