I'm trying to make a A-Z index and would like to filter the response of my custom taxonomy by the first letter of the taxonomy name. So, if I have ['Ana', 'Olina', 'Ford'], i'd like something like wp-json/wp/v2/names/?starts_with=A to give me only 'Ana'. Right now if I do names/?search=A, i'm getting 'Ana' and 'Olina'

I have looked but I haven't found anything similar.

  • Without knowing how you set it up or if you want the return in the actual REST or in the JS there are quite a few factors to consider. But you could use substr() in your custom REST while creating the array – rudtek Jul 16 at 19:00
  • I would like to filter the response itself. I dont want to do JS manipulations but the REST should filter if I add the query parameter in the url. I'm wondering if this can be accomplished using filters, like rest_query_vars, but for taxonomy. I'd be using the returned data in my Vue app. – shubhra Jul 17 at 4:45

You can use the rest_names_query filter to handle the custom starts_with REST API parameter, and use the terms_clauses filter to add a custom SQL clause for searching terms having their name starting with the specified letter (e.g. A or a for /wp/v2/names/?starts_with=A):

add_filter( 'rest_names_query', function( $args, $request ){
    if ( '/wp/v2/names' === $request->get_route() && // check the route
        ( $starts_with = $request->get_param( 'starts_with' ) ) ) {
        $args['name_starts_with'] = $starts_with;
    return $args;
}, 10, 2 );

add_filter( 'terms_clauses', function( $clauses, $taxonomies, $args ){
    if ( ! empty( $args['name_starts_with'] ) ) {
        global $wpdb;

        // "t" below is an alias for the WordPress terms table (wp_terms), and it is set by WordPress.
        $where = $wpdb->prepare( 't.name LIKE %s', $wpdb->esc_like( $args['name_starts_with'] ) . '%' );

        $clauses['where'] .= " AND $where";
    return $clauses;
}, 10, 3 );
  • 1
    It works perfectly, thanks! – shubhra Jul 30 at 23:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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