• 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 : potato

    meta_key : ingredient_recipe_1_ingredient
    meta_value : carrot

    meta_key : ingredient_recipe_2_ingredient
    meta_value : salt

    meta_key : ingredient_recipe_3_ingredient
    meta_value : creme

    There is also that line (which shouldn’t be useful in this case I think) :

    meta_key : ingredient_recipe
    meta_value : 4

    Now 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.

Viewing 1 replies (of 1 total)
Viewing 1 replies (of 1 total)

The topic ‘Search result page : WP_Query with custom fields’ is closed to new replies.