WordPress has a inbuilt search function, and you can type in /?s=Key after your wordpress root location. However, sometimes, if there is only 1 result e.g. for example, the user knows what to search for, it is better to go to that specific post immediately without showing the search page. This certainly will improve the user experience. This is kinda ‘lucky’ button but only works when there is only 1 matched result.
So, just copy the following PHP code at the end of your wordpress theme template (better using child themes), i.e. functions.php.
1 2 3 4 5 6 7 8 9 10 | add_action('template_redirect', 'redirect_single_post_from_search'); function redirect_single_post_from_search() { if (is_search()) { // if it is a search page global $wp_query; if ($wp_query->post_count == 1 && $wp_query->max_num_pages == 1) { // if only 1 result wp_redirect( get_permalink( $wp_query->posts['0']->ID ) ); // go to that page exit; } } } |
add_action('template_redirect', 'redirect_single_post_from_search'); function redirect_single_post_from_search() { if (is_search()) { // if it is a search page global $wp_query; if ($wp_query->post_count == 1 && $wp_query->max_num_pages == 1) { // if only 1 result wp_redirect( get_permalink( $wp_query->posts['0']->ID ) ); // go to that page exit; } } }
That is a quick add-on! No fancy plugins and it works like a charm!
–EOF (The Ultimate Computing & Technology Blog) —
GD Star Rating
loading...
242 wordsloading...
Last Post: How to Compute the Area of Irregular Shapes using ImageJ ?
Next Post: How to Print MySQL Table Summary using PHP?