Sebastian Walter
Sebastian Walter

Reputation: 21

If search query = slug then redirect to page

This was already asked by User Brad, but he seems to have lost interest. I know there are plugins for that (e.g. Curated Search), but I've got too many pages with too many anchors for using one of these.

Let's say I have a WP-Page with the two pages www.homepage.com/cats and www.homepage.com/dogs. www.homepage.com/cats also has the two anchors www.homepage.com/cats#mice and www.homepage.com/cats#birds.

I'd like to redirect if somebody searches for "Cats" to www.homepage.com/cats, if somebody searches for "Cats#mice" to www.homepage.com/cats#mice and so on.

I have fiddled around with this for quite some time now, but I'm a php-noob, hence I'm not surprised that it doesn't work. Here's what I got so far; maybe it is totally dumb, maybe I'm only lacking one line of code.

    <?php
    add_action ('template_redirect', 'one_match_redirect');
    function one_match_redirect() {
        if (is_search()) {
            $query = get_search_query();
            $url = get_home_url( $blog_id = null, $path = $query, $scheme = null );
            if (is_array(@get_headers($url))) {
                wp_redirect ( $url, 303 );
            }
            else {
                new WP_Query ('s=$query');
            }
        }
    }
    ?>

The redirect does work, but on searching e.g. for "lalala", I only get reconnected to www.homepage.com/lalala instead of www.homepage.com/s=lalala. What am I doing wrong? Any help would be greatly appreciated.

Upvotes: 0

Views: 874

Answers (1)

Sebastian Walter
Sebastian Walter

Reputation: 21

Fiddled around some more; now it works. Be warned: I'm still a php-noob, hence the following probably is inelegant code. But at least on my page it does work:

<?php
add_action ('template_redirect', 'one_match_redirect');

function one_match_redirect() {
  global $wpdb;
  if (is_search()) {
    $query = get_search_query();
    $query2 = strstr($query, "#", true);
    $url = get_home_url( $blog_id = null, $path = $query, $scheme = null );
    $pos = strpos($query, '#');
    if ($pos === false) {
      $page = get_page_by_path($query);
      if ($page) {
        wp_redirect ( $url, 303 );
      }
    }
    else {
      $page = get_page_by_path($query2);
      if ($page) {
        wp_redirect ( $url, 303);
      }
    }
  }
}
?>

If I didn't have / care about my anchors, the following would be enough:

<?php
add_action ('template_redirect', 'one_match_redirect');

function one_match_redirect() {
  global $wpdb;
  if (is_search()) {
    $query = get_search_query();
    $url = get_home_url( $blog_id = null, $path = $query, $scheme = null );
    $page = get_page_by_path($query);
    if ($page) {
      wp_redirect ( $url, 303 );
    }
  }
}
?>

Upvotes: 1

Related Questions