0

I'd like to redirect a search result page URL to a specific post. I've tried doing a 301 redirect in the .htaccess but it is not working.

As an example:

I want to redirect permanently the URL http://www.domain.com/?s=keyword to http://www.domain.com/name-of-the-post.html

Is possible to do this in the .htaccess file'

Best

Carles

7

I think it is better that you do this inside the WordPress install, not on the .htaccess. Is not easy to maintain and maybe a problem, if you have more results for a search. You can use the follow source, write in a small plugin and activate. If the search result have only one result, then will rewrite to the single post.

add_action( 'template_redirect', 'fb_single_result' );
function fb_single_result() {

    if (is_search()) {
        global $wp_query;

        if ( 1 === $wp_query->post_count ) {
            wp_redirect( get_permalink( $wp_query->posts['0']->ID ) );
            exit();
        }
    }
}
2
  • Thank you for the answer. But what I want is to redirect some of my result page URLs to specific posts URLs. Is not an issue of having just 1 result for the search. – user44711 Jan 4 '14 at 19:45
  • 1
    Don't forget to exit (or die) after a wp_redirect. – tehlivi Apr 2 '18 at 15:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.