0

I have a custom search in place where I've excluded posts that have a custom field with a specific value, but the search count is including those with the custom field value. How can I get the search count to match the actual number of results?

global $wp_query;

$total_results = $wp_query->found_posts;
if ($total_results > 1) :
    echo '<h5>Search Results for "'. get_search_query( false )  . '": ' .'<span class="results">'.$    total_results.'</span>';

if( have_posts() ) :
    while( have_posts() ) : the_post();   
        $value = get_post_meta($post->ID, 'value', true);
        if ($value != '' &&  get_post_meta($post->ID, 'value', true) == 'value_to_exclude') :        
            the_title();       
        endif;
    endwhile;
endif;

EDIT: I tried since to get the count with a sql statement. The results are always the same number of posts no matter what search keyword I use. How can I get the count to be accurate and exclude the custom field that has a certain value?

$total_results = 

"SELECT count(DISTINCT pm.post_id)
FROM $wpdb->postmeta pm
JOIN $wpdb->posts p ON (p.ID = pm.post_id)
WHERE pm.meta_key = 'approval'
AND pm.meta_value = '1'
AND p.post_type = 'myposttype'
AND p.post_status = 'publish'
";

$count = $wpdb->get_var($total_results);
echo "<p>Count is: $count</p>";
1

If you want to exclude certain posts, wouldn't the conditional be:

 if ($value != '' &&  get_post_meta($post->ID, 'value', true) != 'value_to_exclude')

Anyhow, you're excluding AFTER you run the query. So $total_results will always be 'wrong'. The better approach is to write sql for WP_Query that does the excluding for you. But you didn't include the query, so that cannot be addressed.

  • Thanks, I added a sql statement above since, but getting the same result/count # each time. Any ideas? – amespower Oct 26 '14 at 0:29

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.