Aller au contenu
FR

Redirect the Single Post in the Search condition

Version audio de cet article

With this tutorial, we will enable a function that will allow you to redirect the Single Post if it’s the only search result with a Template Redirect filter.

Inside the function, we will add a condition where if a post is the only result, it will redirect to the post’s permalink.

Redirect the Single Post in the Search condition

add_action('template_redirect', 'via_edirect_single_post'); 
function via_redirect_single_post() { 
    if (is_search()) { 
		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; 
		} 
	} 
}

Visit the Template Redirect page.