Support

Account

Home Forums General Issues Filter products/categories/ by ACF field Reply To: Filter products/categories/ by ACF field

  • I believe my earlier example could work, I have modified the code from the acf-article and I believe this should work:

    $GLOBALS['my_query_filters'] = array( 
    	'field_1' => 'id_category_mercator',
    );
    
    add_action('pre_get_terms', 'my_pre_get_terms', 10, 1);
    function my_pre_get_terms( $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: https://mywebsite/wp-json/wc/v3/products/category?id_category_mercator=merca1
    		$value = explode(',', $_GET[ $name ]);
    		
    		
    		// append meta query
        	$meta_query[] = array(
                'key'		=> $name,
                'value'		=> $value,
                'compare'	=> 'IN',
            );
            
    	} 
    	
    	
    	// update meta query
    	$query->set('meta_query', $meta_query);
    
    }

    All I did was change the $GLOBALS variable at the top to use your acf fieldname, and then I changed the names of the filter and the function.

    I don’t know if this will work because I’m not sure if ACF data on categories is really stored in the term_meta table. But you could add this to your functions.php and try to query the category endpoint with ?id_category_mercator=merca1 we could find out.