TransWikia.com

Using get_posts, I need to use a combination of OR & AND relations

WordPress Development Asked by mstdmstd on October 30, 2021

Using WordPress v4.6, I set up arguments for get_posts() based on price (2 conditions), sku, and categories like this:

[meta_query] => Array
    (
        [relation] => AND
        [0] => Array
            (
                [key] => _price
                [value] => Array
                    (
                        [0] => 0
                        [1] => 5
                    )

                [type] => DECIMAL
                [compare] => BETWEEN
            )

        [1] => Array
            (
                [key] => _price
                [value] => Array
                    (
                        [0] => 50.01
                        [1] => 100
                    )

                [type] => DECIMAL
                [compare] => BETWEEN
            )

        [2] => Array
            (
                [key] => _sku
                [value] => batte
                [compare] => like
            )

    )

[tax_query] => Array
    (
        [0] => Array
            (
                [taxonomy] => product_cat
                [field] => id
                [terms] => Array
                    (
                        [0] => 26
                        [1] => 20
                    )

            )

    )

I set AND relations, but actually I need OR relations between 2 prices and AND relations for the rest of the comparisons.

What is the correct syntax for this query?

One Answer

Nested arrays can be used to create complex Meta Query's.

An example of how this would apply to your situation.

$meta_query_args = array(
    'relation' => 'AND', 
    array(
        // Conditions
    ),
    array(
        'relation' => 'OR',
        array(
            // Conditions
        ),
        array(
            // Conditions
        )
    )
);

For more information check: https://codex.wordpress.org/Class_Reference/WP_Meta_Query

Answered by ngearing on October 30, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP