skip to Main Content

I have this WP_Query code that shows me results if the value of _pre_orders_enabled does not exist or has the value no

What I want is that I also filter it by _stock_status I tried this but it didn’t work.

My code:

$products = new WP_Query( array(
'post_type' => 'product',
'starts_with' => $letra,
'posts_per_page' => -1,
'order' => 'DESC',
    'meta_query'     => array(
        'relation' => 'OR',
        array(
            'key'     => '_pre_orders_enabled',
            'value'   => 'no',
            'compare' => '=',
        ),
        array(
            'key'     => '_pre_orders_enabled',
            'compare' => 'NOT EXISTS',
        ),
    ),
) );

I tried to filter by

array(
    'key'     => '_stock_status',
    'value'   => 'instock',
    'compare' => '=',
),

but it didn’t work

2

Answers


  1. Chosen as BEST ANSWER

    I found the solution

    $products = new WP_Query( array(
        'post_type'      => 'product',
        'starts_with'    => $letra,
        'posts_per_page' => -1,
        'order'          => 'DESC',
        'meta_query'     => array(
            array(
                'key'     => '_stock_status',
                'value'   => 'instock',
                'compare' => '=',
            ),
            array(
                'relation' => 'OR',
                array(
                    'key'     => '_pre_orders_enabled',
                    'value'   => 'no',
                    'compare' => '=',
                ),
                array(
                    'key'     => '_pre_orders_enabled',
                    'compare' => 'NOT EXISTS',
                ),
            ),
        ),
    ) );
    

  2. You can try following code.
    
    $products = new WP_Query( array(
        'post_type'      => 'product',
        'starts_with'    => $letra,
        'posts_per_page' => -1,
        'order'          => 'DESC',
        'meta_query'     => array(
            'relation' => 'AND', 
            array(
                'key'     => '_pre_orders_enabled',
                'value'   => 'no',
                'compare' => '=',
            ),
            array(
                'key'     => '_stock_status',
                'value'   => 'instock',
                'compare' => '=',
            ),
        ),
    ) );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search