Get WP Posts Meta Query

User
_highlight yes/no get wp post which has no or empty
Assistant
To retrieve WordPress posts that have an empty or non-existent `_highlight` meta key, you can use the following query with `WP_Query`. Here’s an example of how to do this:

$args = array(
    'post_type'      => 'post', // Change to your custom post type if needed
    'meta_query'     => array(
        array(
            'key'     => '_highlight',
            'compare' => 'NOT EXISTS', // This will get posts where the meta key does not exist
        ),
        array(
            'key'     => '_highlight',
            'value'   => '',           // This will get posts where the meta key is empty
            'compare' => '=',          // Optional: to also include empty values
        ),
    ),
    'posts_per_page' => -1, // Retrieve all posts, adjust as needed
);

$query = new WP_Query($args);

if ($query->have_posts()) {
    while ($query->have_posts()) {
        $query->the_post();
        // Your code to handle the post
        echo '<h2>' . get_the_title() . '</h2>';
    }
    wp_reset_postdata();
} else {
    echo 'No posts found.';
}

### Explanation:
– **post_type**: Specify the post type to query. Default is `post`.
– **meta_query**: An array that defines multiple meta queries:
– The first array checks if the `_highlight` meta key does not exist.
– The second array checks if the `_highlight` meta key exists but is empty.
– **posts_per_page**: Set to `-1` to retrieve all matching posts.

### Note:
You can adjust the `post_type` and other parameters in the `$args` array according to your specific needs.

Leave a Comment

Your email address will not be published. Required fields are marked *