0

I am building a meta query array and all fields for the user are optional so some might not have any data. But there is also an option which requires a date query. I am still checking to see if this is working but not sure as of yet. Is this correct and if not, what would be the right way to do it? Not sure if there needs to be an OR condition in here somewhere.

$meta_query = [];
$date_query = [];

if ( $gender != '' ) {
    $meta_query[] = [
        'key' => 'gender',
        'value' => $gender,
        'compare' => '='
    ];
}

if ( $age != '' ) {
     $meta_query[] = [
        'key' => 'age',
        'value' => $age,
        'compare' => '='
    ];
}

if ( $userDate != 0 ) {
    $date_query[] = [
        'year' => $year,
        'month' => $month
    ];
}

$args = [
    'post_type' => 'person',
    'fields' => 'ids',
    'posts_per_page' => -1,
    'post_status' => 'any',
    'meta_query' => $meta_query,
    'date_query' => $date_query

];

$data = get_posts($args);
3
  • 1
    Post meta queries are expensive but you've used get_posts instead of WP_Query, aside from caching the result, you should set the suppress_filters option to false otherwise this query will be totally uncached even with caching plugins. You should also change posts_per_page to a high number you never expect to reach but know your server can handle, not -1. Also gender could easily be part of a tax_query which would provide another performance boost, same with age, use taxonomies not post meta for data you need to group/search/filter by
    – Tom J Nowell
    May 19 at 15:06
  • @TomJNowell, thanks for your info. Ah right, supress_filters is only default of false for wp_query and not get_posts. I don't think I am following with your tax_query suggestion as the fields I am referring to are custom meta fields and not taxonomy fields? May 19 at 16:08
  • 1
    that's right, you would need to change how that data is stored to use custom taxonomies instead of post meta. Post meta is optimised for when you know which post ID the meta belongs to, but doing the reverse gets very expensive. How expensive depends on the size of your post meta table, so it will seem lightning fast on a site with a handful of posts, but it may bring down databases on very large sites. Taxonomies were built for the opposite problem, finding post IDs when you already know the name/value
    – Tom J Nowell
    May 19 at 16:44

0

Your Answer

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

Browse other questions tagged or ask your own question.