phpwordpressadvanced-custom-fieldsmeta-query

another meta_query in pre_get_posts() that returns 0 results


For years I've been using stack overflow and I could always find an answer (or half answers that I could stitch together), but this time I really can't figure this out...

So, I have an ACF Post Object field (inicia_areas) that associates one or more posts of Custom Post Type (CPT) B to CPT A posts.

The objective is to be able to filter posts in the archive of CPT A that have CPT B posts associated to them. Nothing too fancy :)

I'm using pre_get_posts() hook, since I was able to filter posts by category this way.

For tests purposes I simplified the pre_get_posts() function and hardcoded the value in the meta_query. I then associated three CPT A posts to the post with the slug "central-de-compras" to get some results.

The code:

function wpsites_query($query)
{
    if ($query->is_main_query() && !is_admin()) {

        if (is_post_type_archive('iniciativas')) {

            // these vars return arrays from form
            global $filter_areas, $filter_temas;

            // -> Categories Filter - WORKING
            if ($filter_temas && count($filter_temas) > 0) {
                $cat_ids = [];
                foreach ($filter_temas as $temas) {
                    array_push($cat_ids, get_term_by('slug', $temas, 'category')->term_id);
                }
                $query->set('category__in', $cat_ids);
            }

            // -> ACF Filter - RETURNING NO POSTS
            if ($filter_areas && count($filter_areas) > 0) {
                $query->set(
                    'meta_query',
                    array(
                        array(
                            'key'     => 'inicia_areas',
                            'value'   => 'central-de-compras',
                            'compare' => '='
                        )
                    )
                );
            }
            $query->set('posts_per_page', 12);
        }

        return $query;
    }
}
add_action('pre_get_posts', 'wpsites_query');

The if($filter_areas... is returning true, so the query is being set. I tried the values with "post-name" and "ID" and compare with "=", "LIKE", "==", "EXIST". Converted the value to an array and use the "IN" compare, but nothing. Zero results.

I didn't post the query output because TLDR, but if it helps, I'll post it.

Thanks in advance! Pedro


Solution

  • The meta_query is checking inicia_areas meta is equal to central-de-compras, but the meta data's value is an array of integers, which is why the query does not return any results. Adjust your meta data or your query so that the types match or the logic expects the correct type.