0

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 );

1 Answer 1

3

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...

and the filter name rest_cpt_query is just an example as well: in this case cpt is the slug of your post type. change it to post, page or your_custom_post_type_slug and the filter will run on the respected post type.

link to the filter in use.

3
  • This is what I ended up doing but using $request['city']
    – Laurent
    Dec 22, 2020 at 23:30
  • If the answer solved your problem you should upvote it and mark it as accepted. This helps users with similar questions find a solution. Dec 23, 2020 at 6:29
  • @Laurent yeah, i just made it the super save way. so i check, if the value is actually there. otherwise php would throw errors ala array key does not exist, yada yada. safety first ;)
    – honk31
    Nov 30, 2022 at 15:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.