• Hello,

    i create some posts and added a meta-value with the key “example”.

    now i want to select all posts where this meta-key is empty or have the value “test”

    how can i do that?

    here i can either use a meta-key or not but not both…

    $args = array(
            'posts_per_page' => 5,
            'offset' => 0,
            'category' => '',
            'category_name' => '',
            'orderby' => 'title',
            'order' => 'ASC',
            'include' => '',
            'exclude' => '',
            'meta_key' => '',
            'meta_value' => '',
            'post_type' => 'mytype',
            'post_mime_type' => '',
            'post_parent' => '',
            'author' => '',
            'post_status' => 'publish',
            'suppress_filters' => true
        );
        get_posts($args);

Viewing 3 replies - 1 through 3 (of 3 total)
  • You want something that looks like this….

    $args = array(
    	'post_type'  => 'product',
    	'meta_query' => array(
    		'relation' => 'OR',
    		array(
    			'key'     => 'color',
    			'value'   => 'blue',
    			'compare' => 'NOT LIKE',
    		),
    		array(
    			'key'     => 'price',
    			'value'   => array( 20, 100 ),
    			'type'    => 'numeric',
    			'compare' => 'BETWEEN',
    		),
    	),
    );
    $query = new WP_Query( $args );

    Original source of this code and other examples: https://codex.www.ads-software.com/Class_Reference/WP_Query

    Thread Starter MaWe4585

    (@mawe4585)

    i just found an example using get_posts

    $args = array(
        'post_status'=>'publish',
        'post_type' => 'mytype',
        'meta_query' => array(
                array(
                    'key' => 'example',
                    'compare' => 'NOT EXISTS'
                ),
            )
        );
        return get_posts($args);

    seems it uses the same arguments like WP_Query, i guess it internally uses WP_Query.

    The default set of posts are returned using the wp_query class, so you are correct. The example I provided was creating a new wp_query object from scratch.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘select all posts where meta-key doesn't exist or has certain value’ is closed to new replies.