• Resolved Fotis K

    (@f_kalafatishotmailcom)


    I’ve been trying to implement a custom search that won’t only search posts but also media (by they’re titles and custom fields).
    Before going for the whole thing, I performed a little test: I wanted the search to display only posts of type ‘attachment'(media) and I thought I could achieve this by putting the following piece of code in my functions.php:

    function SearchFilter($query) {
      if ($query->is_search) {
        $query->set('post_type', 'attachment');
        $query->set('post_status', 'inherit');
        $query->set('post_parent', NULL);
      }
      return $query;
    }
    
    add_filter('pre_get_posts','SearchFilter');

    Unfortunately, no luck. When searching it doesn’t display the (unattached) media files. Any idea what might be wrong?

Viewing 1 replies (of 1 total)
  • Thread Starter Fotis K

    (@f_kalafatishotmailcom)

    I guess asking the post_parent to be NULL was the problem. My final working code(searching posts and media) is the following and should be placed in functions.php:

    function SearchFilter($query) {
      if ($query->is_search) {
        $query->set('post_type', array('attachment','post','page'));
        $query->set('post_status', array('publish','inherit'));
      }
      return $query;
    }
    add_action('pre_get_posts','SearchFilter');
Viewing 1 replies (of 1 total)
  • The topic ‘Custom Search Query on media(attachments)’ is closed to new replies.