How to Change Search Permalink in WordPress

WordPress allows you to enable pretty URLs for your website within a few clicks. But, this doesn’t change Search URL. By default, WordPress Search URL looks something like this,

http://localhost/blog/?s=keyword

Using a small amount of code you can make it look pretty.

http://localhost/blog/search/keyword

Useful Read: How to Add a Favicon to Your WordPress Blog

To change the search permalink for your WordPress website paste the following code in your functions.php file.

//change WordPress permalink
function cws_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', 'cws_nice_search_redirect' );

Source: https://wordpress.org/plugins/nicesearch/

2 Comments

Leave a Comment.