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().'" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener">';
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
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
try passing max_num_pages to the function:
next_posts_link('Older Entries »', $loop->max_num_pages);
Method 2
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().'" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener">';
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;
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0