WordPress – get_search_link() enhancer

Published on November 30, 2010 by , in Wordpress

You already know that when performing the search in WordPress, the URL becomes something with:
/?s=lorem+ipsum in the end.

An odd fact was that get_search_link() returns something like /search/lorem+ipsum. So if you’re using a theme that creates a link to the search results page you’ll receive a different URL compared to the one that you receive when performing an actual search (two pages at different URLs showing the exact same content is no good).

Therefore I created a small snippet that fixes this when inserted in the functions.php file from your theme – making get_search_link() return the exact same URL that one would receive when performing a search.


function simple_search_link($link)
{
$link = str_replace('/search/','/?s=',$link);
$link = rtrim($link, '/');
return $link;
}
add_filter('search_link','simple_search_link');

I’ve used the str-replace to replace the /search/ with /?s=, and the rtrim function to strip the trailing /.
Now the exact same URL is used for both the get_search_link as actual searches.

This would also mean a better performance if you’re using caching.