Query_vars support in Rest API

I am trying to make query_vars work in rest api. In my code bellow if I call wp-json/wp/v2/cpt?city=test, my debug output always returns an empty string.

?php
/**
 * Plugin Name: Test
 * Author:      Gecka [email protected]
 * License:     GNU General Public License v3 or later
 * License URI: http://www.gnu.org/licenses/gpl-3.0.html
 */

function cpt_init() {
    $args = [
        'label'               = 'Custom post',
        'supports'            = [ 'title', 'revisions', 'custom-fields' ],
        'show_in_rest'        = true,
        'hierachical'         = false,
        'public'              = true,
        'exclude_from_search' = true,
        'show_ui'             = true,
    ];
    register_post_type( 'cpt', $args );
}
add_action( 'init', 'cpt_init' );

function cpt_register_query_vars( $vars ) {
    $vars[] = 'city';
    return $vars;
}
add_filter( 'query_vars', 'cpt_register_query_vars' );

function cpt_posts_where( $where, WP_Query $wp_query ) {
    if('cpt' !== $wp_query-get('post_type') ) {
        return $where;
    }

    // debug output
    var_export( $wp_query-get('city') );
    
    return $where;
}
add_filter( 'posts_where', 'cpt_posts_where', null, 2 );

Topic query-variable rest-api wp-query Wordpress

Category Web


correct me, if i'm wrong, but query vars are not processed in REST requests. but there is other ways to make this work. not really sure, if this will help with your problem but hopefully it is at least a push in the right direction

function so380236_rest_cpt_query($args, $request)
{
    $query_params = $request->get_query_params();

     if (!array_key_exists('city', $query_params)) {
        //$args is your WP_Query[$args] array
        //example:
        $args['posts_per_page'] = 12;
    }

    return $args;
}

add_filter('rest_cpt_query', 'so380236_rest_cpt_query', 10, 2);

the posts_per_page is just a jibberish example for you to understand, you could create/manipulate meta and or tax queries etc...

link to the filter in use.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.