1

I would like the search to show only published posts and attachments (the attachments are photographs taken directly from the media library).

The trouble is, when I specify that the post_status must be publish, it excludes the attachments because they don't have a parent and therefore don't have any status.

Is there any other way to exclude posts marked as "private" or "draft?"

Here's my current code:

function SearchFilter($query) {
if ($query->is_search && $query->is_main_query() || is_archive() )  {
$query->set('post_status', array( 'publish', 'inherit' ));
$query->set( 'post_type', array( 'post', 'attachment' ) );
}
return $query;
}

add_filter('pre_get_posts','SearchFilter');
  • $query->is_search should be $query->is_search() .. i guess it's a typo you have done while asking. – bravokeyl May 18 '16 at 5:24
  • @bravokeyl Whilst the method call is the correct way, search is a valid class property and will still work. – TheDeadMedic May 18 '16 at 9:43
  • @TheDeadMedic, got it. – bravokeyl May 18 '16 at 9:44
  • 1
    Querying post status either publish or inherit should work - are you sure your code runs? As in, does the condition evaluate true for when you're testing? – TheDeadMedic May 18 '16 at 9:45
  • Ok, I think the problem was actually a custom search function competing with the plugin "Search Everything," which is how I was getting my categories and tags to populate in the search. @TheDeadMedic, you're right on both accounts. It works with and without () and inherit does work, even though the attachments don't have a parent. Good to know, thanks! – BlueHelmet May 18 '16 at 19:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.