I looked through the interwebz but couldn't find a solution.
I am creating a website with custom post types where posts also include custom post meta (through ACF).
I am creating an archive file and I want to implement some filters (filter post by category and two different custom fields.
To even see the custom posts (called "mowcy") in category template I have added this snippet to my functions file:
Functions.php
function custom_post_type_cat_filter($query) {
if ( !is_admin() && $query->is_main_query() ) {
if ($query->is_category()) {
$query->set( 'post_type', array( 'post', 'mowcy' ) );
}
}
}
So now I uploaded a simple archive template to see how it works:
Archive.php
<?php
get_header();
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
echo 'Title:' . get_the_title();
} else {
echo 'Sorry, no posts';
}
get_footer();
?>
Now, here is where the problem starts:
If I specify the arguments in the code and use custom query to show custom posts with a specific custom fields value "EN" (an ACF field "languages" with multiple checkboxes for different languages), it works perfectly:
// Specify query parameters
$args = array(
'post_type' => 'mowcy',
'meta_query' => array(
array(
'key' => 'languages',
'value' => '"EN"',
'compare' => 'LIKE'
)
)
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) // ... Beginning of the loop
However, if I print the same arguments to use in the URL (using http_build_query with $args), which looks like this:
post_type=mowcy&meta_query%5B0%5D%5Bkey%5D=languages&meta_query%5B0%5D%5Bvalue%5D=%22EN%22&meta_query%5B0%5D%5Bcompare%5D=LIKE
after reverting archive.php to use main query and URL parameters again, and using the above parameters, the meta_query is completely ommited from the query, and it just shows all of the posts of the custom type "mowcy". I can add a category parameter to URL and it works fine, but meta_query is still completely ignored.
What am I missing? Does query function ignore meta_queries on custom post types by default? How to fix this?
Also, as I said at the beginning, I plan to filter the posts by an additional second custom value too (so a second additional meta_query). Will this be an additional problem (while searching for a solution I have seen a few mentions that you need to manually merge two meta queries in such case)?
Thanks in advance for any kind of assistance.
meta_query
is a private query var which means it is registered, but will by default not be parsed from the URL. And if you must make the var parseable from the URL, you'd need to add the var to the public query vars like you would with custom query vars.