1

I'd like to get all posts for which the custom field hidden is NOT present. This does not work:

$postsForSitemap = get_posts(array(
    'numberposts' => -1, 
    'orderby' => 'modified', 
    'post_type' => array('post', 'page'), 
    'order' => 'DESC', 
    'meta_key' => 'hidden', 
    'meta_compare' => '!=')
);

because meta_compare is about the meta_value, not the key.

I haven't found in the documentation https://developer.wordpress.org/reference/classes/wp_query/#custom-field-post-meta-parameters how to get all posts that don't have a specific custom field.

How to do this?

1 Answer 1

2
+50

You could use NOT EXISTS as the value for comparem, you could also check for empty value if thats relevant

This code only checks if hidden meta does not exists

$postsForSitemap = get_posts([
    'numberposts'  => -1, 
    'orderby'      => 'modified', 
    'post_type'    => ['post', 'page'], 
    'order'        => 'DESC', 
    'meta_key'     => 'hidden', 
    'meta_compare' => 'NOT EXISTS'
];

This checks is hidden meta does not exists OR has no value

$postsForSitemap = get_posts([
    'numberposts' => -1, 
    'orderby'     => 'modified', 
    'post_type'   => ['post', 'page'], 
    'order'       => 'DESC', 
    'meta_query'  => [
        'relation' => 'OR',
        [
            'key'     => 'hidden',
            'compare' => 'NOT EXISTS',
        ],
        [
            'key'   => 'hidden',
            'value' => ''
        ]
    ]
];
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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