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 |1 Answer
Reset to default 2You 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 );
substr()
in your custom REST while creating the array – rudtek Commented Jul 16, 2019 at 19:00