Skip to content

Instantly share code, notes, and snippets.

@bamadesigner
Last active February 14, 2016 17:51
Show Gist options
  • Save bamadesigner/78c04d8d73f43892f7bd to your computer and use it in GitHub Desktop.
Save bamadesigner/78c04d8d73f43892f7bd to your computer and use it in GitHub Desktop.
A method for detecting when WP_Query is being run for a REST API call.
<?php
/**
* Filter allowed query vars for the REST API.
*
* This filter allows you to add or remove query vars from the final allowed
* list for all requests, including unauthenticated ones. To alter the
* vars for editors only, {@see rest_private_query_vars}.
*
* @param array {
* Array of allowed WP_Query query vars.
*
* @param string $allowed_query_var The query var to allow.
* }
*/
add_filter( 'rest_query_vars', 'filter_rest_query_vars' );
function filter_rest_query_vars( $valid_vars ) {
// Add our REST API flag
$valid_vars[] = 'wp_rest_api';
return $valid_vars;
}
/**
* Filter the query arguments for a request.
*
* Enables adding extra arguments or setting defaults for a post
* collection request.
*
* @see https://developer.wordpress.org/reference/classes/wp_user_query/
*
* @param array $args Key value array of query var to query value.
* @param WP_REST_Request $request The request used.
*/
add_filter( 'rest_post_query', 'filter_rest_post_query', 10, 2 );
function rest_post_query( $args, $request ) {
// FYI: 'post' in the filter name, 'rest_post_query', is the
// name of the post type and can be interchanged.
// Add a flag for us to use later
$args[ 'wp_rest_api' ] = true;
// Return the filtered query args
return $args;
}
////////////
// ABOVE IS ALL YOU NEED FOR DETECTION
////////////
// BELOW IS AN EXAMPLE OF HOW YOU WOULD IMPLEMENT THE DETECTION IN ANOTHER FILTER
////////////
/**
* Filter all query clauses at once, for convenience.
*
* Covers the WHERE, GROUP BY, JOIN, ORDER BY, DISTINCT,
* fields (SELECT), and LIMITS clauses.
*
* @since 3.1.0
*
* @param array $clauses The list of clauses for the query.
* @param WP_Query &$this The WP_Query instance (passed by reference).
*/
add_filter( 'posts_clauses', 'filter_posts_clauses', 10, 2 );
function filter_posts_clauses( $pieces, $query ) {
// Only filter the clauses if we're using the REST API
if ( ! $query->get( 'wp_rest_api' ) ) {
return $pieces;
}
// Filter the clauses
// Return the pieces
return $pieces;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment