我目前正在更新一个旧的WordPress主题(一个独立的主题,不是任何官方主题的产物)。尝试构建分页时,我发现创建一个既适用于存档又适用于搜索的功能时存在一些问题。第一个代码段可以很好地处理归档(类别、循环等):
function pagination_bar() {
global $wp_query;
$total_pages = $wp_query->max_num_pages;
if ($total_pages > 1){
$current_page = max(1, get_query_var(\'paged\'));
echo paginate_links(array(
\'base\' => get_pagenum_link(1) . \'%_%\',
\'format\' => \'page/%#%\',
\'current\' => $current_page,
\'total\' => $total_pages,
\'prev_text\' => __(\'« Previous page\'),
\'next_text\' => __(\'Next page »\'),
));
}
}
问题是,如果我在搜索结果页面中使用,链接最终会
domain.com/?s=QUERYpage/2
(虽然应该是
domain.com/page/2/?s=query
)
因此,我创建了一个自定义函数,用于搜索中的分页:
function pagination_bar_search() {
global $wp_query;
$total_pages = $wp_query->max_num_pages;
if ($total_pages > 1){
$current_page = max(1, get_query_var(\'paged\'));
echo paginate_links(array(
\'base\' => get_home_url() . \'%_%\',
\'format\' => \'/page/%#%/\',
\'current\' => $current_page,
\'total\' => $total_pages,
\'prev_text\' => __(\'« Previous page\'),
\'next_text\' => __(\'Next page »\'),
));
}
}
这两个功能都可以正常工作,但您对如何将这两个功能结合起来,使其在存档和搜索中都能正常工作有何想法?
我正在使用最新的WordPress(5.2.3)。
这是search.php
循环功能:
<?php
$paged = (get_query_var(\'paged\')) ? get_query_var(\'paged\') : 1;
if ($wp_query->max_num_pages > 1)
echo \'Page \' . $paged.\' of \'.$wp_query->max_num_pages;
?>
...
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
...
<?php endwhile; ?>
<?php pagination_bar_search(); ?>
最合适的回答,由SO网友:Sally CJ 整理而成
从Codex:
要将分页添加到搜索结果和存档中,可以使用以下示例:
<?php
global $wp_query;
$big = 999999999; // need an unlikely integer
echo paginate_links( array(
\'base\' => str_replace( $big, \'%#%\', esc_url( get_pagenum_link( $big ) ) ),
\'format\' => \'?paged=%#%\',
\'current\' => max( 1, get_query_var(\'paged\') ),
\'total\' => $wp_query->max_num_pages
) );
?>
基于此,我修改了你的函数:
function pagination_bar( $query = null ) {
global $wp_query;
$total_pages = $query ?
$query->max_num_pages :
$wp_query->max_num_pages;
if ( $total_pages > 1 ) {
$big = 999999999; // need an unlikely integer
$current_page = max( 1, get_query_var( \'paged\' ) );
echo paginate_links( array(
\'base\' => str_replace( $big, \'%#%\', esc_url( get_pagenum_link( $big ) ) ),
\'format\' => \'?paged=%#%\',
\'current\' => $current_page,
\'total\' => $total_pages,
\'prev_text\' => __( \'« Previous page\' ),
\'next_text\' => __( \'Next page »\' ),
) );
}
}
它在档案和搜索结果方面都运行良好。
我还添加了对自定义查询的支持(即。new WP_Query
), 例如,您可以:
$my_query = new WP_Query( array( ... ) );
pagination_bar( $my_query );