0

I need your help with Custom URLs in Custom Search Results (Wordpress).

I have this URL http://domain.com/?s=&categories=489&locations=310 which get me search results.

I can replace IDs with Category and Location "Slug" to look like this

http://domain.com/find/category-in-location/ and get same search results as with old URL address.

Note: I use Yoast SEO plugin in Wordpress.

Thank you for your help and cooperation.

4

You can get close to what you want by using the template_redirect hook.

function my_custom_search_url_rewrite() {
  if ( is_search() && ! empty( $_GET['s'] ) ) {
    wp_redirect( home_url( "/search/" ) . urlencode( get_query_var( 's' ) ) );
    exit();
  } 
}
add_action( 'template_redirect', 'my_custom_search_url_rewrite' );

Then you can use a URL like http://domain.com/search/category+location/.

If you then want to change search into find you could use the search_rewrite_rules filter like this.

function my_custom_search_url( $search_rewrite ) {
  if( !is_array( $search_rewrite ) ) { 
    return $search_rewrite;
  }

  $new_array = array();

  foreach( $search_rewrite as $pattern => $s_query_string ) {
    $new_array[ str_replace( 'search/', 'find/', $pattern ) ] = $s_query_string;
  }

  $search_rewrite = $new_array;

  unset( $new_array );

  return $search_rewrite;
}
add_filter("search_rewrite_rules", "my_custom_search_url");

Then you can use a URL like http://domain.com/find/category+location/.

Note: Remember to flush or re-save your permalinks.

I'm sure, with some more tinkering, you could get a bit closer to what you asked for but this is as close I've got so far.

EDIT: Sorry forgot to mention... if you use the function for the search_rewrite_rules filter you'll need to change the my_custom_url_rewrite function to this.

function my_custom_search_url_rewrite() {
  if ( is_search() && ! empty( $_GET['s'] ) ) {
    wp_redirect( home_url( "/find/" ) . urlencode( get_query_var( 's' ) ) );
    exit();
  } 
}
add_action( 'template_redirect', 'my_custom_search_url_rewrite' );
  • Dear Mr. James Barrett, please see my next post. Thank you for your help and cooperation. – Tomas Jun 20 '15 at 16:16

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.