Created
June 19, 2017 03:17
-
-
Save vishalbasnet23/dadd45e5a0ea48c92e3eaaed52079f30 to your computer and use it in GitHub Desktop.
Add filter by name to WP REST Posts End Point.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
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['post_per_page'] = $filter['posts_per_page']; | |
} | |
global $wp; | |
$vars = apply_filters( 'query_vars', $wp->public_query_vars ); | |
foreach ( $vars as $var ) { | |
if ( isset( $filter[ $var ] ) ) { | |
$args[ $var ] = $filter[ $var ]; | |
} | |
} | |
return $args; | |
} |
How to filter with LIKE on product_name?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice work