¿Quiere redirigir la búsqueda al post si sólo hay un resultado de búsqueda? Este fragmento mejora la experiencia de búsqueda in situ al eliminar la necesidad de hacer clic.
Instrucciones:
Todo lo que tienes que hacer es añadir este código al archivo functions.php de tu tema o en un plugin específico del sitio:
add_action('template_redirect', 'single_result'); function single_result() { if (is_search()) { global $wp_query; if ($wp_query->post_count == 1) { wp_redirect( get_permalink( $wp_query->posts['0']->ID ) ); } } }
Nota: Si es la primera vez que añade fragmentos de código en WordPress, consulte nuestra guía sobre cómo copiar / pegar correctamente fragmentos de código en WordPress, para no romper accidentalmente su sitio.
Si le ha gustado este fragmento de código, por favor, considere revisar nuestros otros artículos en el sitio como: Mejorar la experiencia de búsqueda por defecto de WordPress – la revisión completa de WP de búsqueda.
I get a syntax error, unexpected ‘$wp_query’ (T_VARIABLE) when i copy paste in your code in the functions.php file. So what i have is a custom post type named cars with 4 taxonomies and i have made an archive page that uses the grid plugin and the search and filter pro plug-in. All works well but i want to have a redirected to the post page instead if i have only one result in the archive. Can you give some hints ? Thanks !
Thanks!
[…] really like this one – thanks WP Snipp! When a user searches your website and there is only one result the user is taken straight to the […]
[…] [Source] […]
Nice code but I would make one improvement… change
if ($wp_query->post_count == 1) to
The original code breaks pagination when there is only one post left on the next page and redirects to it instead of showing it. eg. If a post archive is set to show 10 post per page and 11 results are returned then instead of showing the last post it redirects to it.if ($wp_query->found_posts == 1)
this is working properly, thanks!
Glad it helped 🙂
[…] [Source: WPSNIPP] […]
Your sample worked fine for me, everything appears to work working.
Hey, me too now. Sorry. Thanks.
no problem 🙂