Support

Account

Home Forums General Issues Content Filtering Using Fields – Issues Reply To: Content Filtering Using Fields – Issues

  • add_action('pre_get_posts', 'my_pre_get_posts', 10, 1);
    
    function my_pre_get_posts( $query ) {
    	
    	// bail early if is in admin
    	if( is_admin() ) return;
    	
    	
    	// bail early if not main query
    	// - allows custom code / plugins to continue working
    	if( !$query->is_main_query() ) 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;
    			
    		}
    		
    		
    		// get the value for this filter
    		// eg: http://www.website.com/events?city=melbourne,sydney
    		$value = explode(',', $_GET[ $name ]);
    
    		
    		// append meta query
    	foreach( $value as $val )
        {
        	$meta_query = [
    	 [
    	     'key'		=> $name,
                'value'		=> '"' . $val . '"',
                'compare'	=> 'LIKE',
            ],
    	];
    }
            
    	} 
    	
    	
    	// update meta query
    	$query->set('meta_query', $meta_query);
    
    }