Support

Account

Home Forums Front-end Issues Filter by field name Reply To: Filter by field name

  • John, thank you for your help, i figured out what the problem was, after I used your meta_query code, it didn’t work, but then I started to do a bit more research, and it turns out the problem was in the $value var.

    I changed
    $value = explode(',', $_GET[ $name ]);

    to $value = $_GET[ $name ] and it worked flawlessly.

    To help anyone else, my whole code was:

    function lang_pre_get_posts( $query ) {
    
        // array of filters (field key => field name)
        $GLOBALS['my_query_filters'] = array( 
            'field_1'	=> 'event_country'
        );
    	
    	// bail early if is in admin
    	if( is_admin() ) {	
    		return;
    	}
    	
    	// get meta query
    	$meta_query = $query->get('meta_query');
    
    	// loop over filters
    	foreach( $GLOBALS['my_query_filters'] as $key => $name ) {
    		
    		// continue if not found in url
    		if( empty($_GET[ $name ]) ) {
    			continue;
    		}
    
    		if( ! $query->is_post_type_archive() ) return;
    		
    		// get the value for this filter
    		$value = $_GET[ $name ];
    		
    		// append meta query
            $meta_query[] = array(
              'relation' => 'OR',
                array(
                  'key' => 'event_country',
                  'value' => '"'.$value.'"',
                  'compare' => 'IN'
    
               ),
                array(
                  'key' => 'event_country',
                  'value' => '"'.$value.'"',
                  'compare' => 'LIKE'
                ),
    
            );
            
    	} 
    
    	// update meta query
    	$query->set('meta_query', $meta_query);
    }
    
    add_action('pre_get_posts', 'lang_pre_get_posts', 10, 1);