0

I'm creating simple API endpoint to fetch custom post type items with specified category and tags.

function my_awesome_func( $data ) {
  $posts = get_posts( array(
        'post_type' => 'faq',
        'numberposts' => 10,
        'tax_query' => array(
            'relation' => 'AND',
                array(
                        'taxonomy' => 'category',
                        'field' => 'slug',
                        'terms' => array($data['cat']) 
                ),
                array(
                    'taxonomy' => 'post_tag',
                        'field' => 'slug',
                        'terms' => array($data['tag']) 
                ),
            )
        )
  );
 
  if ( empty( $posts ) ) {
    return null;
    }

        
        foreach( $posts as $post ) {
            $id = $post->ID; 

            $posts_data[] = (object) array( 
                    'id' => $id, 
                    'title' => $post->post_title,
                    'content' => $post->post_content
            );
        }                  
    
    return $posts_data;
}

add_action( 'rest_api_init', function () {
  register_rest_route( 'test/v1', '/faq/cat=(?P<cat>[a-zA-Z0-9_,]+)/tag=(?P<tag>[a-zA-Z0-9_,]+)', array(
    'methods' => 'GET',
    'callback' => 'my_awesome_func',
  ) );
} );

It works fine with this request: ...wp-json/test/v1/faq/cat=cars/tag=big but I would like to make it more flexible, by adding only category, or only tags ...wp-json/test/v1/faq/cat=cars and by adding multiple tags (i.e separated by comma): ...wp-json/test/v1/faq/cat=cars/tag=big,blue

Thanks in advance for help.

1 Answer 1

1

You need to register separate routes for each scenario you want to cover (ie, cat & tag, just cat, or just tag), all done in the single add_action call. The regex you have will support the comma separated tags.

The next thing to do is change how you set the 'term' parameter as part of the 'tax_query' array parameter. It's expecting an array of strings, currently you are passing a single string of comma separated values (ie, 'tag1,tag2'). You can pass the result of using explode() to convert the string to an array.

You will also need to implement some conditional logic around setting the 'tax_query' array parameter based on what route is used.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.