If pagination does not work on the search page
I recently encountered a small, unclear, and unpleasant problem - pagination did not work on the search page in one of the templates. Pagination was organized by the wp-pagenavi plugin. Interestingly, the cause of this strange pagination behavior was the Theme (template) itself, because it worked fine in the default one.
The issue with the pagination on the search page was that when switching to page 2, for example, the URL would lose the search query parameter ?s={search query}, so instead of page/2?s={search query}, it would become just page/2. As a result, it would redirect to the homepage instead.
Attempts to find the main cause were not successful; everything seemed to be in order. Since I couldn't solve the problem at its root, I took a workaround and created this hack:
// Hack to fix non-working pagination on the search page in WordPress
add_filter( 'get_pagenum_link', 'kama_fix_search_pagination' );
function kama_fix_search_pagination( $result ){
$glue = strpos($result, '?') ? '&' : '?';
return $result . $glue . 's=' . urlencode( $_REQUEST['s'] );
}
I added this code at the beginning of the search.php theme file, and after that, everything started working.