2

I want to exclude some posts from the home page. So I want to use meta data, and filter all posts that are signed by meta_value=0. Like this:

$args = array(
'posts_per_page'=>28,
'meta_query' => array(
array(
    'key' => 'show_on_home',
    'value' => '0',
    'compare' => 'NOT LIKE'
    )
)                   
);
$query = new WP_Query( $args );                         

So, if I sign some post with meta_key=0 it will not apear.
The problem is that I have a lot off posts that don't have meta data at all, and I don't want to filter them.

2
  • You could reverse the logic and query posts that have meta key 'show_on_home' + meta value '1' – diggy Jan 11 '13 at 13:43
  • @diggy, A lot of posts don't have meta data at all, so I can not do it – Shimon S Jan 11 '13 at 13:55
2

WordPress 3.5 and up supports EXISTS and NOT EXISTS comparison operators.

compare (string) - Operator to test. Possible values are '=', '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN', 'EXISTS' (only in WP >= 3.5), and 'NOT EXISTS' (also only in WP >= 3.5). Default value is '='.

http://codex.wordpress.org/Class_Reference/WP_Query

So...

array(
    'key' => 'show_on_home',
    'compare' => 'NOT EXISTS'
)

... should show all posts that don't have that key. I think that is what you are trying to do.

3
  • Thank you very much! to inckude posts that have value=1 on this key, I use this code: $args = array( 'posts_per_page'=>28, 'meta_query' => array( 'relation' => 'OR', array( 'key' => 'show_on_home', 'value' => '0', 'compare' => 'NOT EXISTS' ), array( 'key' => 'aa_show_on_home', 'value' => '1' ) ) ); $query = new WP_Query( $args ); – Shimon S Jan 12 '13 at 16:52
  • Yes, but if you don't have too many with that '1' value, you'd get better performance by resetting that value and doing without that extra condition. ORs are not very efficient. Just something to consider. – s_ha_dum Jan 12 '13 at 16:53
  • Yes. I cheked it. it took 0.32 seconds vs 0.12 second without OR. Thank you very much! – Shimon S Jan 12 '13 at 19:11

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.