Search result page : WP_Query with custom fields
-
Hi everyone.
I’m working on a cooking website.
I needed to add a custom field “ingredient” to my posts, so I installed the ACF Pro (advanced custom fields) plugin.
I added a Repeater text field “ingredients”, so now I can add 1 or more ingredients to each post.I created a search form with 3 text fields (each one corresponding to an ingredient).
Basically the idea is to display only the posts containing exactly those 3 ingredients (or less if only one or 2 fields are filled).My problem is about using Wp_query to display the good posts.
In the database, I can easily find those ingredients in the ‘postmeta’ table.
It looks like this :meta_key : ingredient_recipe_0_ingredient
meta_value : potatometa_key : ingredient_recipe_1_ingredient
meta_value : carrotmeta_key : ingredient_recipe_2_ingredient
meta_value : saltmeta_key : ingredient_recipe_3_ingredient
meta_value : cremeThere is also that line (which shouldn’t be useful in this case I think) :
meta_key : ingredient_recipe
meta_value : 4Now my problem :
If someone fills the 3 text fields with “potato”, “creme”, “garlic”, I would like to execute a query which finds the posts that contain at least those 3 ingredients.
I tried to use WP_Query and WP_Meta_Query to do that, but I cannot find a way.In SQL, my query should look like this :
SELECT * FROM wp_posts WHERE ID IN ( SELECT post_id FROM wp_postmeta WHERE meta_key LIKE 'ingredient_recipe_%' AND meta_value = 'potato') AND ID IN ( SELECT post_id FROM wp_postmeta WHERE meta_key LIKE 'ingredient_recipe_%' AND meta_value = 'creme') AND ID IN ( SELECT post_id FROM wp_postmeta WHERE meta_key LIKE 'ingredient_recipe_%' AND meta_value = 'garlic')The problem is the “LIKE” part of the object WP_Meta_Query.
I think it’s only possible to do a “LIKE” comparaison on the meta_value. I didn’t find how to do it on the meta_key.This is what I tried :
$meta_query = new WP_Meta_Query(array( array( 'key' => 'ingredients_recette_%', 'value' => 'potato', 'compare' => 'LIKE' ) ));But I think the SQL equivalent is this :
SELECT post_id FROM wp_postmeta WHERE meta_key = 'ingredient_recipe_%' AND meta_value LIKE 'potato'Is there a way to do that?
Thanks in advance.
The topic ‘Search result page : WP_Query with custom fields’ is closed to new replies.