admin管理员组

文章数量:1419624

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.

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.

Share Improve this question asked Jul 16, 2019 at 8:59 shubhrashubhra 1489 bronze badges 2
  • 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 Commented Jul 16, 2019 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 Commented Jul 17, 2019 at 4:45
Add a comment  | 

1 Answer 1

Reset to default 2

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 );

本文标签: WP REST APILimit the taxonomy search to the first letter