wordpress search by attachment title

Funny enough, there many search enhancement plugins for wordpress, but It seems none of them can do what I want : return posts if one its child attachments matches the search query. It's easy enough when you think about it but the code below will save you the hour I spent looking for it on google .

<?php
 
 
 
add_filter('posts_join', 'po_search_join' );
add_filter('posts_where', 'po_search_where' );
add_filter('posts_groupby', 'po_search_groupby' );

function po_search_join( $join )
{
  global  $wpdb, $wp_query;
       
  if($wp_query->is_search  ) {
    $join .= " left JOIN {$wpdb->prefix}posts p2  ON  {$wpdb->prefix}posts.ID = p2.post_parent  "   ;
 
  }

  return $join;
}

function po_search_where( $where )
{ global  $wpdb, $wp_query;    
  if($wp_query->is_search    ) {
      $s=get_query_var('s');
    $where = $where . " or (p2.post_title LIKE '%" . addslashes_gpc($s)  . "%'
    ) ";
   }                  
 
  return $where;
}

function po_search_groupby( $groupby )
{
  global  $wpdb, $wp_query;  

  if( !$wp_query->is_search ) {     return $groupby; }

  // we need to group on post ID
  $mygroupby = "{$wpdb->posts}.ID";

  if( preg_match( "/$mygroupby/", $groupby )) {
    // grouping we need is already there
    return $groupby;
  }

  if( !strlen(trim($groupby))) {
    // groupby was empty, use ours
    return $mygroupby;
  }

  // wasn't empty, append ours
  return $groupby . ", " . $mygroupby;
}
 
0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *