Home Forums General Issues How to filter products with ACF in rest API


How to filter products with ACF in rest API

  • Hello,
    I can use the rest api to receive all my product with this link :
    I created custom fields the the ACF plugin.
    I can see the fields in the result
    Now I want to be able to filter the results with a link like this

    I have to add some code in my Functions.php file but I’m doing something wrong or with the bad hook.

    Could you please help me with a sample ?

    Thanks in advance,

  • Previously, I’ve added some code to my functions file:

    // Create custom query for API
    if( ! function_exists( 'product_meta_request_params' ) ) :
    	function product_meta_request_params( $args, $request ){
            $args += array(
                'meta_key'		=> $request['meta_key'],
                'meta_value'	=> $request['meta_value'],
                'meta_query'	=> $request['meta_query'] == 1 ? array(
                    "key"		=> "model",
                    "value"		=> array(''),
    				"compare"	=> 'NOT IN',
            ) : $request['meta_query']
    	    return $args;
    	add_filter( 'rest_product_query', 'product_meta_request_params', 99, 2 );

    My API URL then looked like:' . $current_page . '&per_page=10&meta_query=1

  • Hello @jarvis,
    Thanks for your help.
    I use this code :

    function my_pre_get_products( $query ) {
    	// do not modify queries in the admin
    	if( is_admin() ) {
    		return $query;
    	// only modify queries for 'product' post type
    	if( isset($query->query_vars['post_type']) && $query->query_vars['post_type'] == 'product' ) {
    		// allow the url to alter the query
    		if( isset($_GET['id_article_mercator']) ) {
        		$query->set('meta_key', 'id_article_mercator');
    			$query->set('meta_value', $_GET['id_article_mercator']);
    	return $query;
    add_action('pre_get_posts', 'my_pre_get_products');

    Now I have a response on this url : https://mywebsite/wp-json/wc/v3/products?id_article_mercator=42771

    Now I want to have the same result for a category of the products.
    This url returns all the categories.

    I want to be able to filter a custom field added by ACF

    Do you have an idea what to add as function for this ?
    What’s strange also, for the products, I can see in the rest api result the metadata with the values added by ACF
    For the category, the metadata aren’t visible.
    In the database the values are stored in termmeta for the categories and in postmeta for the products.
    If I’m right, the product is a post and the category is a taxonomy.

    Thanks in advance,

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.