Combining WordPress pagination functions for archives and search results
I am currently modernising an old WordPress theme (a standalone theme, not a child of any official themes). Trying to build pagination I am finding some issues creating one function that works for both archives and search. The first snippet works fine with archives (categories, loops, etc):
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 »'),
));
}
}
The problem is that if I use in search results pages the links end up being domain.com/?s=QUERYpage/2
(whilst it should be domain.com/page/2/?s=query
)
So I created a custom function just for pagination in search:
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 »'),
));
}
}
Both work correctly, but do you have any ideas for how I can combine the 2 functions and make one that works correctly for both archives and search?
I'm on the latest WordPress (5.2.3).
This is the search.php
loop function:
?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(); ?
Topic paginate-links pagination Wordpress
Category Web