Det finns tillfällen när du söker på en WordPress blogg, du får bara ett objekt i resultatet. Beroende på hur organiserad din site är, bör detta vara det objekt som användaren letade efter i alla fall. En av våra användare frågade om det fanns ett sätt att redirecta till posten om sökningen bara resulterar i en matcha. I den här artikeln kommer vi att visa dig hur du redirectar användare till posten när sökningen bara ger en matcha.
Allt du behöver göra är att öppna ditt temas functions.php-fil och klistra in följande snippet.
add_action('template_redirect', 'one_match_redirect'); function one_match_redirect() { if (is_search()) { global $wp_query; if ($wp_query->post_count == 1) { wp_redirect( get_permalink( $wp_query->posts['0']->ID ) ); } } }
Nu måste du vara uppmärksam på att vissa användare inte förväntar sig den här funktionen. Så det kan skrämma bort dem.
Syed Balkhi says
Hey WPBeginner readers,
Did you know you can win exciting prizes by commenting on WPBeginner?
Every month, our top blog commenters will win HUGE rewards, including premium WordPress plugin licenses and cash prizes.
You can get more details about the contest from here.
Start sharing your thoughts below to stand a chance to win!
Casey Lessard says
Worked for me. I run a local search engine using WordPress and I have been trying to find this solution for some time. Does exactly as described. Thank you so much!
Eric says
I want to make it so when some searches a specific phrase it redirects to an easter egg, like if someone searches ”I see dead people” specifically it’ll redirect them to a URL I can define.
Nebulas Website Design says
Thanks for this piece of code it made my client very happy and I didn’t thnk it could be done. However it’s not working for us we are using the Relevanssi search plugin should it work with this?
carlos says
What if I want to redirect any search query to the most relevant post no matter what the number of posts the search returns? I’d really like to be able to do that.
Editorial Staff says
Get rid of the if conditional from the code above, and it should do it.
Administratör
CalebZahnd says
This is handy. Thanks!