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 |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 );
本文标签: WP REST APILimit the taxonomy search to the first letter
版权声明:本文标题:WP REST API - Limit the taxonomy search to the first letter 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745316563a2653182.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
substr()
in your custom REST while creating the array – rudtek Commented Jul 16, 2019 at 19:00