Support

Account

Home Forums ACF PRO Meta query the repeater field

Helping

Meta query the repeater field

  • Hi everyone,

    I have a custom post type “monument” which has a repeater field “styles” with two meta fields “style” and “interet”.
    In other words each “monument” may have an undefined pair of “style” / “interet” values.

    I can already alter the main loop to filter the “monument” list on “style” or “interet” fields using pre_get_posts and replacing the “=” in where clause by a “LIKE”.

    That’s great, but if I use the two filters “style” and “interet” I want them to match in the same row.
    Let’s say we have :
    “monument 1” :
    ( “style” = “style 1”, “interet = “interet 1” )
    ( “style” = “style 2”, “interet = “interet 1” )
    ( “style” = “style 3”, “interet = “interet 2” )
    “monument 2” :
    ( “style” = “style 2”, “interet = “interet 2” )
    ( “style” = “style 3”, “interet = “interet 1” )

    If I query “style” = “style 2” AND “interet = “interet 2” it returns the two “monument” as these meta values are found in both posts.
    But how can I check if the values belong to the same row? I should then return only the second “monument” because the first one doesn’t have the row ( “style” = “style 2”, “interet = “interet 2” )

    Here is the code. I wan’t to stay in the main loop and use these filters on archive page.

    Thanks a lot for any idea.

    add_action('pre_get_posts', 'my_pre_get_posts');
    function my_pre_get_posts( $query )
    {
    	// validate
    	if( is_admin() )
    	{
    		return;
    	}
    
    	if( !$query->is_main_query() )
    	{
    		return;
    	}
    
    	// get original meta query
    	$meta_query = $query->get('meta_query');
    
            if( !empty($_GET['interet']) || !empty($_GET['style']) )
            {
            	$interets = explode(',', $_GET['interet']);
    			$styles = explode(',', $_GET['style']);
    			
            	//Add our meta query to the original meta queries
    	    	$meta_query[] = array(
    				'relation' => 'AND',
    				array(
    					'key' => 'styles_%_interet',
    					'value' => $interets,
    				),
    				array(
    					'key' => 'styles_%_style',
    					'value' => $styles,
    				)
    			);
            }
    
    	// update the meta query args
    	$query->set('meta_query', $meta_query);
    
    	return;
    }
    
    add_filter('posts_where', 'my_posts_where');
    function my_posts_where( $where )
    {
    	$where = str_replace("meta_key = 'styles_%_interet'", "meta_key LIKE 'styles_%_interet'", $where);
    	$where = str_replace("meta_key = 'styles_%_style'", "meta_key LIKE 'styles_%_style'", $where);
    
    	return $where;
    }
Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.