Support

Account

Home Forums ACF PRO Archive with ajax custom field filter : Error 500 Reply To: Archive with ajax custom field filter : Error 500

  • Well, if it can help somebody, this is my working code :

    // array of filters (field key => field name)
    $GLOBALS['my_query_filters'] = array(
    	'field_5cb6ef1f75209'  => 'alcool',
    	'field_5cb74afb68539'  => 'caracteristiques',
    );
    
    // action
    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
    	$meta_query = array(
    		'relation' => 'AND',
    	);
    	$i = 0;
    	foreach( $GLOBALS['my_query_filters'] as $key => $name ) {
    
    		// continue if not found in url
    		if( empty($_GET[ $name ]) ) {
    			continue;
    		}
    
    		$i++;
    
    		$meta_query[$i] = array(
    			'relation' => 'OR',
    		);
    
    		// get the value for this filter
    		$values = explode( ",", $_GET[ $name ] );
    
    		foreach( $values as $value ) {
    			$meta_query[$i][] = array(
    				'key'      => $name,
    				'value'    => $value,
    				'compare'  => 'LIKE',
    			);
    
    		}
    	}
    	// update meta query
    	$query->set('meta_query', $meta_query);
    	return;
    
    }
    

    Just a question, is there a way to “ajaxify” this ? With no page reload ?