-
Notifications
You must be signed in to change notification settings - Fork 48
/
plugin.php
53 lines (45 loc) · 1.69 KB
/
plugin.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?php
/**
* Plugin Name: WP REST API filter parameter
* Description: This plugin adds a "filter" query parameter to API post collections to filter returned results based on public WP_Query parameters, adding back the "filter" parameter that was removed from the API when it was merged into WordPress core.
* Author: WP REST API Team
* Author URI: http://v2.wp-api.org
* Version: 0.1
* License: GPL2+
**/
add_action( 'rest_api_init', 'rest_api_filter_add_filters' );
/**
* Add the necessary filter to each post type
**/
function rest_api_filter_add_filters() {
foreach ( get_post_types( array( 'show_in_rest' => true ), 'objects' ) as $post_type ) {
add_filter( 'rest_' . $post_type->name . '_query', 'rest_api_filter_add_filter_param', 10, 2 );
}
}
/**
* Add the filter parameter
*
* @param array $args The query arguments.
* @param WP_REST_Request $request Full details about the request.
* @return array $args.
**/
function rest_api_filter_add_filter_param( $args, $request ) {
// Bail out if no filter parameter is set.
if ( empty( $request['filter'] ) || ! is_array( $request['filter'] ) ) {
return $args;
}
$filter = $request['filter'];
if ( isset( $filter['posts_per_page'] ) && ( (int) $filter['posts_per_page'] >= 1 && (int) $filter['posts_per_page'] <= 100 ) ) {
$args['posts_per_page'] = $filter['posts_per_page'];
}
global $wp;
$vars = apply_filters( 'rest_query_vars', $wp->public_query_vars );
// Allow valid meta query vars.
$vars = array_unique( array_merge( $vars, array( 'meta_query', 'meta_key', 'meta_value', 'meta_compare' ) ) );
foreach ( $vars as $var ) {
if ( isset( $filter[ $var ] ) ) {
$args[ $var ] = $filter[ $var ];
}
}
return $args;
}