WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Custom Search Query on media(attachments) (2 posts)

  1. Fotis K
    Member
    Posted 2 years ago #

    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?

  2. Fotis K
    Member
    Posted 2 years ago #

    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');

Topic Closed

This topic has been closed to new replies.

About this Topic