简体   繁体   English

在WordPress的REST API v2中按类别过滤自定义帖子类型

[英]Filter custom post type by category in REST API v2 in WordPress

I am creating an Android app using the WP API. 我正在使用WP API创建一个Android应用。 I managed to show a custom post type in the REST API which can be viewed in: 我设法在REST API中显示了一个自定义帖子类型,可以在以下位置查看它:

http://localhost/wordpress/wp-json/wp/v2/property

Now I want to filter properties by their category, eg villa , home , rent , etc. I have tried the following, but it does not work: 现在,我想按属性分类属性,例如villahomerent等等。我尝试了以下操作,但是不起作用:

http://localhost/wordpress/wp-json/wp/v2/property?filter[category_name]=villa` 
http://localhost/wordpress/wp-json/wp/v2/property?filter[category]=apartment`

I was running into this issue as well with my custom post types. 我的自定义帖子类型也遇到了这个问题。

You need to query by your custom taxonomy (eg. property_categories, or whatever you named it in your register_taxonomy() function) and then by the term. 您需要通过自定义分类法(例如,property_categories或您在register_taxonomy()函数中命名的名称)进行查询, 然后通过术语进行查询。

&filter[taxonomy]=property_categories&filter[term]=villa

This saved my own day 这挽救了我自己的一天

mysite.com/wp-json/wp/v2/property?property-status=33

then this was my call in my themes functions file 然后这是我在主题函数文件中的调用

    //get custom post types in the WP-API v2
//for mobile app
add_filter( 'register_post_type_args', 'sb_add_cpts_to_api', 10, 2 );
function sb_add_cpts_to_api( $args, $post_type ) {
if ( 'property' === $post_type ) {
$args['show_in_rest'] = true;
}
return $args;
}


//to add taxonomy for properties to API result
    add_action( 'init', 'sb_add_taxes_to_api', 30 );
    function sb_add_taxes_to_api() {
    $taxonomies = get_taxonomies( 'property-city', 'property-type', 'property-status' );
      foreach( $taxonomies as $taxonomy ) {
            $taxonomy->show_in_rest = true;
            $taxonomy->name;
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM