WP_Query và next_posts_link


7

Tôi không thể tìm ra cách làm cho next_posts_link () hoạt động trong WP_Query tùy chỉnh của mình. Đây là chức năng:

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();
}

Bất cứ ai có thể cho tôi biết những gì tôi đang làm sai?

Cảm ơn

Câu trả lời:


11

hãy thử chuyển max_num_pages cho hàm:

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

10

next_posts_linkvà previous_posts_link, cũng như một số hàm khác, sử dụng một biến toàn cục được gọi là $wp_query. Biến này thực sự là một thể hiện của đối tượng WP_Query. Tuy nhiên, khi bạn tạo trình khởi tạo WP_Query của riêng chúng tôi, bạn không có biến toàn cục này $wp_query, đó là lý do tại sao phân trang sẽ không hoạt động.

để khắc phục rằng bạn lừa $wp_querytoàn cầu

//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;
Khi sử dụng trang web của chúng tôi, bạn xác nhận rằng bạn đã đọc và hiểu Chính sách cookie và Chính sách bảo mật của chúng tôi.
Licensed under cc by-sa 3.0 with attribution required.