Creating complex queries with WP_Query in WordPress

Here’s a complex query which we’ve built using WP_Query. It should:

  1. Ignore post id 191

AND

Read More
  1. Select all posts with ‘reihenfolge’ <= 18

AND

  1. Ignore posts without a featured image

AND

  1. Order them randomly

Here is the code:

$args_projekte = array(
        'post_type' => 'projekt',
        'posts_per_page' => 18,
        'meta_query' => array('relation' => 'AND',
                                array('post__not_in' => array(191)),
                                array('meta_key' => 'reihenfolge',  
                                      'meta_value_num' => '18',
                                      'meta_compare' => '<='),
                                array('key' => '_thumbnail_id')
                            ),  
        'orderby' => 'rand'
        );

However, ALL posts are being shown in a random order. 'reihenfolge <=18' seems to be being ignored.

What are we missing here?

Related posts

1 comment

  1. Your meta_query is completely wrong. All you parameters inside your arrays is invalid.

    • post__not_in should be outside your meta_query

    • meta_key, meta_value_num and meta_compare are all invalid paramters inside a meta_query. This parameters is used outside a meta_query

    You query should look something like this

    $args_projekte = array(
        'post_type' => 'projekt',
        'posts_per_page' => 18,
        'post__not_in' => array( 191 ),
        'orderby' => 'rand',
        'meta_query' => array(
            'relation' => 'AND',
            array(
                'key' => 'reihenfolge',
                'value' => '18',
                'compare' => '<='
            ),
            array(
                'key' => '_thumbnail_id'
            ),
        ),
    );
    

Comments are closed.