Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I filter the Query Loop Block by multiple custom fields instead of one?

Tags:

php

wordpress

I have just followed this tutorial to filter a Query Loop block by a custom field. It's functionining as expected, and I am using the code below to filter the front-end.

My question is, how do I filter by multiple meta queries? For example, I'd like to show posts if colours_ornamental is true AND another key is set to true as well.

I have written queries before, however it's my first time working with the query loop block. Thank you in advance for your help.

add_filter( 'pre_render_block', 'chilli_collection_pre_render_block', 10, 2 );

function chilli_collection_pre_render_block( $pre_render, $parsed_block ) {

    if ( !empty($parsed_block['attrs']['namespace']) && 'chilli-collection' === $parsed_block['attrs']['namespace'] ) {

        add_filter( 'query_loop_block_query_vars',

            function( $query, $block ) {

                $query['meta_key'] = 'colours_ornamental';
                $query['meta_value'] = '1';
                $query['meta_compare'] = '=';
                $query['posts_per_page'] = '-1';
                $query['orderby'] = 'title';
                $query['order'] = 'ASC';
                return $query;
            },

        10, 2 );
    }
    return $pre_render;
}

I attempted to merge my knowledge about queries with the way the tutorial was laid out, however I found that there is simply a gap to bridge.

like image 443
Noëlle Steegs Avatar asked Jan 17 '26 18:01

Noëlle Steegs


1 Answers

Using the meta_query parameter allows you to specify multiple filters for meta data.

Something like this (untested):

add_filter( 'query_loop_block_query_vars', static function ( $query ) {
    $query['meta_query'] = array(
        'relation' => 'AND',
        array(
            'key' => 'colours_ornamental',
            'value' => '1',
            'compare' => '=',
        ),
        array(
            ...
        ),
    );

    return $query;
} );
like image 169
Caleb Avatar answered Jan 19 '26 08:01

Caleb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!