WordPress rewrite rules for pagination on search page

If you want to add custom rewrite rules I’d recommend you to use available functions like add_rewrite_rule().

But!

You don’t really need to add custom rewrite rules to achieve what you want.

WordPress supports nice slugs for search queries out of the box. It just needs to be “activated”.

First, you need to define the URL slug like this:

function wpse293111_search_base() {
  $GLOBALS['wp_rewrite']->search_base="store";
}

add_action( 'init', 'wpse293111_search_base' );

After that, you need to redirect requests ?s=<searchterm> to the new URLs. You can use something like this to do so:

function wpse293111_nice_search_redirect() {
  global $wp_rewrite;
  if ( !isset( $wp_rewrite ) || !is_object( $wp_rewrite ) || !$wp_rewrite->using_permalinks() ) {
    return;
  }

  $search_base = $wp_rewrite->search_base;

  if ( is_search() && !is_admin() && strpos( $_SERVER['REQUEST_URI'], "/{$search_base}/" ) === false ) {
    wp_redirect( home_url( "/{$search_base}/" . urlencode( get_query_var( 's' ) ) ) );
    exit();
  }
}

add_action( 'template_redirect', 'wpse293111_nice_search_redirect' );

The Nice Search plugin does exactly this redirect, so you can also just install this plugin if you want and only keep the first function to change the search base.

Benefits:

  • Using built-in functionality
  • No problems with pagination
  • You can still modify search queries using pre_get_posts hook if needed

Note: