Search code examples
mysqlwoocommerceorders

WooCommerce $orders = wc_get_orders() Getting Meta


QUESTION 1: Regarding, $orders = wc_get_orders(), how do I enter parameters for the mysql query using OR and AND for the 'meta_query'?

    $orders = wc_get_orders(
        array(
            'limit'   => -1,
            'return'  => 'objects',
            'orderby' => 'date',
            'order'   => 'ASC',
            'meta_query'    => array(
                array(
                    'key'   => 'custom_meta_data',
                    'value' => 'hello kitty',
                    'compare'   => 'LIKE'
                ),
            ),
            'type'      => 'shop_order',
        )
    );

I tried the following and got fewer orders than above. It appears to use AND for the 'meta_query' because there were fewer results than above. How can I get that to do an OR such as value like 'hello kitty' OR value like 'hi dog'?

    $orders = wc_get_orders(
        array(
            'limit'   => -1,
            'return'  => 'objects',
            'orderby' => 'date',
            'order'   => 'ASC',
            'meta_query'    => array(
                array(
                    'key'   => 'custom_meta_data',
                    'value' => 'hello kitty',
                    'compare'   => 'LIKE'
                ),
                array(
                    'key'   => 'custom_meta_data',
                    'value' => 'hi dog',
                    'compare'   => 'LIKE'
                ),

            ),
            'type'      => 'shop_order',
        )
    );

This gave a fatal error…

    $orders = wc_get_orders(
        array(
            'limit'   => -1,
            'return'  => 'objects',
            'orderby' => 'date',
            'order'   => 'ASC',
            'meta_query'    => array(
                array(
                    'key'   => 'custom_meta_data',
                    'value' => array('hello kitty', 'hi dog'),
                    'compare'   => 'LIKE'
                ),
            ),
            'type'      => 'shop_order',
        )
    );

QUESTION 2: The above uses the same meta_key. Can you include if I need AND or OR example for a different meta_key?

QUESTION 3: Am I correct to assume that 'LIKE' will surround the entry with '%hi kitty%'? How would I get the exact phrase?

Thank YOU!


Solution

  • Use the relation key to specify AND or OR explicitly:

                'meta_query'    => array(
                    'relation' => 'OR',
                    array(
                        'key'   => 'custom_meta_data',
                        'value' => 'hello kitty',
                        'compare'   => 'LIKE'
                    ),
                    array(
                        'key'   => 'custom_meta_data',
                        'value' => 'hi dog',
                        'compare'   => 'LIKE'
                    ),
    
                ),