問題描述
我不知道如何使我的自定義 WP_Query 中的 next_posts_link() 工作。這是功能:
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();
}
有誰能告訴我我做錯了什麼?
謝謝
最佳解決方案
嘗試透過 max_num_pages 功能:
next_posts_link('Older Entries »', $loop->max_num_pages);
次佳解決方案
next_posts_link 和 previous_posts_link,以及其他幾個功能,使用一個名為 $wp_query 的全域性變數。該變數實際上是 WP_Query 物件的一個例項。但是,當您建立我們自己的 WP_Query 例項化時,您沒有這個全域性變數 $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;
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。