Reputation: 372
I want to make a loop to create a request WP_meta_query (source : https://codex.wordpress.org/Class_Reference/WP_Meta_Query) but I have hard time to get the expected result.
Here is the context : People can sarch for posts in the search form. I also had custom fields on the posts via the magic-field-2 plugin. When the people search, they can write something and check some checkboxes to get a more accurate result.
The easiest way I found to manage this is to extract data from the search and do a WP_meta_query to find what I need.
The actual syntax for this kind of search looks like this :
query_args = array( 'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'foo_key',
// 'value' => 'foo',
// 'compare' => 'LIKE',
),
array(
'key' => 'bar_key',
),
) );
$meta_query = new WP_Meta_Query();
$meta_query->parse_query_vars( $query_args );
$mq_sql = $meta_query->get_sql(
'post',
$wpdb->posts,
'ID',
null
);
As I told in my topic, I'm trying to loop from my search results and recreate a similar array.
First, I splited the array in two.
Array ( [s] => John )
Array ( [enseignant] => on [travailleur] => on )
The search term in one and my checkboxes in the other. As You can see, I search John in "enseignant" and "travailleur"
To get thing working out, I wrapped up everything in this kind of query :
$requete = array();
$i = 0;
foreach($les_cases as $key => $value) {
$requete[] = array('key'=>$key, 'value' => $le_terme_de_la_recherche['s'], 'compare'=>'IN');
$i++;
}
$args = array(
'post_type' => 'post',
'meta_query' => array(
'relation' => 'OR',
$requete
)
);
When I do a print of my request, it shows something like this :
Array
(
[0] => Array
(
[key] => enseignant
[value] => John
[compare] => IN
)
[1] => Array
(
[key] => travailleur
[value] => John
[compare] => IN
)
)
Array
(
[post_type] => post
[meta_query] => Array
(
[relation] => OR
[0] => Array
(
[0] => Array
(
[key] => enseignant
[value] => John
[compare] => IN
)
[1] => Array
(
[key] => travailleur
[value] => John
[compare] => IN
)
)
)
)
You see that there is alot of [0] in my arrays and I suspect this to create some errors in my query.
After all, should I take compare LIKE, IN or = if I want to be able to select a part of the datas. In exemple, if I wrote John it would be able to give me John Doe.
If some one could help me to manage this puzzle I would be gracefull.
Upvotes: 0
Views: 750
Reputation: 7352
You have one extra array in your meta_query.
Instead of doing
$args = array(
'post_type' => 'post',
'meta_query' => array(
'relation' => 'OR',
$requete
)
);
try
$args = array(
'post_type' => 'post',
'meta_query' => array_merge( // merge instead of pushing a new array
array( 'relation' => 'OR' ), // this must be an array
$requete
)
);
And make sure your meta keys are correct, of course.
(btw, the [0]'s are just the array keys, you can't have an array without keys).
Upvotes: 2