0

I have posts with the following categories:

A category that is a year(2017,2018...2022), a category that is type:(worldwide,Europe, local)

I am trying to give users in the frontend advanced search ability they have two multiselect dropdown, they can pick a year or several. and a type. (both of these are technically categories)

For example select post from cat 2017 or cat 2018 AND that are (cat=Europe or cat=local)`

I am having trouble mixing the "and" and "or" efficiently... in get_posts.

For instance I can do something like:

$posts = get_posts(array( 'category__and' => array(1,10) ));  // assuming 10=category Europe, 1 =category 2016,

So I just do a loop like

Foreach $year in list of years:
  foreach $type in list of types
     get_posts(array( 'category__and' => array($year,$type) ));

Is there a more efficient way to combine my conditions?

Thanks

1
  • This seems efficient enough. However I would consider keeping an index of all posts by previous years (2016, 2017) in wp_options, and search the index with additional 'Europe' or other category. This will prevent the scan of ALL posts, and will speed up the result. I guess a speedup of > 60%
    – Mulli
    Commented Jan 25, 2023 at 17:43

1 Answer 1

0

You could use a taxonomy query to make it cleaner and easier to read; I'm not sure if this would be any faster than the way you're doing it, though.

$args = array(
    'tax_query' => array(
        'relation' => 'AND',
        array(
            'taxonomy' => 'category',
            'field'    => 'name',
            'terms'    => array( 'Europe', 'local' ),
            'operator' => 'IN',
        ),
        array(
            'taxonomy' => 'category',
            'field'    => 'name',
            'terms'    => array( '2017', '2018' ),
            'operator' => 'IN',
        ),
    ),
    'per_page' => 10000,
);
$posts = get_posts( $args );

...should get you any posts (well, the first 10000 posts) that are in ( ( 2017 || 2018 ) && ( Europe || local ) ). (I think; the code is untested, so you may have to tweak it.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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