1

I would like to return all posts when the tax_query['terms'] is empty.

$args = array(
        'post_type' => 'product',
        'posts_per_page' => 15,
        'paged' => $paged,
        'post__not_in' => $exclude,
        's' => $filter,
        'tax_query' => array(
            array(
                'taxonomy' => 'product_cat',
                'field'    => 'term_id',
                'terms'    => array(),
            ),
        ),
    );

Unfortunately I didn't find solution for the problem. As you can see the array is empty: 'terms' => array(),but I would like to return all posts. How can I achive that?

  • 1
    Check if the array is empty before adding the tax query. – Milo Jul 24 '15 at 21:49
4

As already hinted by @Milo, check if you have terms before appending your tax_query

You can try the following: (Requires PHP 5.4+ due to short array syntax, revert to old syntax if necessary)

$args = [
    'post_type' => 'product',
    'posts_per_page' => 15,
    'paged' => $paged,
    'post__not_in' => $exclude,
    's' => $filter,
];

// Append our tax-query if we have terms. Make sure it is a valid string or array
$term = 'DEFINE YOUR TERM HERE';
if ( $terms ) {
    $args['tax_query'] = [
        [
            'taxonomy' => 'product_cat'
            'terms' => $terms,
        ]
    ];
}

$q = new WP_Query( $args );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.