Friday, December 13, 2013

Wordpress: How to get search results if your pages have subpages embedded in them?

In this case the default Wordpress search is not applicable as we do not want to link subpages directly. We need to find their parent pages and link only to them.

You can achieve this using the following code in your search.php:

 <?php  
      //Get search results  
      global $query_string;  
      $query_args = explode("&", $query_string);  
      $search_query = array();  
      foreach($query_args as $key => $string) {  
           $query_split = explode("=", $string);  
           $search_query[$query_split[0]] = urldecode($query_split[1]);  
      };  
      $search = new WP_Query($search_query);  
      //Set exceptions that you don't want listed  
      $exceptions = array();  
      //Create the results array  
      $result_links = array();  
      foreach($search->posts as $result) {  
           //Get top-most parent page ID  
           if ($result->post_parent)     {  
                $ancestors=get_post_ancestors($result->ID);  
                $root=count($ancestors)-1;  
                $parent = $ancestors[$root];  
           } else {  
                $parent = $result->ID;  
           }  
           //Check if the result is already in the result array or in exceptions  
           $link = '<a href="'.get_page_link($parent).'">'.get_the_title($parent).'</a>';  
           if(!in_array($link, $result_links) and !in_array($link, $exceptions)) {  
                $result_links[] = $link;  
           };  
      };  
      //List the result  
      print_r($result_links);  
 ?>