I want to send visitors to my search.php after a search to display list of posts. If there is only one search result, user can directlyto the post in question(something like GOOGLE's I am Feeling Lucky Button)
Thank you all.
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It only takes a minute to sign up.
Sign up to join this communityAdd this snippet to your functions.php
function redirect_the_single_post() {
if (is_search() && is_main_query()) {
global $wp_query;
if ($wp_query->post_count == 1 && $wp_query->max_num_pages == 1) {
wp_redirect( get_permalink( $wp_query->posts['0']->ID ) );
exit;
}
}
}
add_action('template_redirect', 'redirect_the_single_post' );
hope this will help you!!
if (is_search() && is_main_query()) {
. And the permalink can also be generated from $GLOBALS['post']->ID
- but that is not so much shorter. ;) But it is about retrieving a property of an element of an array. Your code is about retrieving a property of an element of an array, which is a property of another object.