7

I cannot figure out how to make next_posts_link() work within my custom WP_Query. Here is the function:

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

Can anyone tell me what I am doing wrong?

Thanks

11

try passing max_num_pages to the function:

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

next_posts_link and previous_posts_link , as well as several others functions, make use of a global variable called $wp_query. This variable is actually an instance of the WP_Query object. However, when you create our own instantiation of WP_Query, you don’t have this global variable $wp_query, which is why paging will not work.

to fix that you trick $wp_query global

//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;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.