Search code examples
phpwordpressmetaposts

Posts not being returned in Wordpress search filter


I'm writing a Wordpress query to filter search results.

I want to remove results using the templates logged_in_mentor_only_template.php, logged_in_only_template.php (and also from two restricted categories).

This query works BUT stops any posts being returned. Very odd, pages are returned but posts are not. (I haven't added the category filtering yet as I have no posts to filter!)

I've tried adding post_type filter with posts and pages listed but still nothing.

Any help appreciated.

 query_posts(array_merge($wp_the_query->query, array(
    'meta_query' => array(
        array(
            'key' => '_wp_page_template',
            'value' => 'logged_in_mentor_only_template.php',
            'compare' => '!='
        ),
        array(
            'key' => '_wp_page_template',
            'value' => 'logged_in_only_template.php',
            'compare' => '!='
        )
    )
)));

Solution

  • You search for _wp_page_template Posts won't have any _wp_page_template.
    So it will only get pages. Because it will return only post/pages which have a _wp_page_template set. So you need to check for a non existing meta key.

    In WP 3.5 the compare value 'NOT EXISTS' will be added.

    Until 3.5 I would suggest the following work around. Don't add these meta query values. But check for them in the loop:

    while (the_posts()): the_post();
        if (get_post_meta(GET_THE_ID(), '_wp_page_template', true) == 'logged_in_mentor_only_template.php' || get_post_meta(GET_THE_ID(), '_wp_page_template', true) == 'logged_in_mentor_only_template.php')
            continue; // skipp the rest of this round
        //Do the rest of your loop
    endwhile;
    

    A second option would be to get all the post that do have the templates.
    Get all the ID's from this query.
    Then do a new wp_query where you exclude the ID's of the previously fetched query.

    best option
    These work arounds Are not good for performance.
    The best option would be to wait a few weeks for WP 3.5, it should be released somewhere in december.