How to use "getEntityRecords" for specific taxonomy terms
Asked Answered
A

2

6

I'm trying to use "getEntityRecords" to get custom post types from specific terms of taxonomy. For "post" I can use "categories" attribute in "query" object, like below:

getEntityRecords( 'postType', 'post', {per_page: 3, categories: [1,2,3] } )

and it works fine. But how to do the same for taxonomy terms?

I've tried use "terms" attribute in query object but this does not work.

getEntityRecords( 'postType', 'my_post_type', {per_page: 3, terms: [1,2,3] } )

I want to get only posts in specific term but now I get all custom posts.

Asuncionasunder answered 10/9, 2019 at 21:59 Comment(0)
L
6

Yes, there isn't a lot of documentation for using the data module and using it often feels like guesswork. However, through experimentation, I've been able to work out the following:

To get all posts:

getEntityRecords( 'postType', 'post' )

To get custom post type:

getEntityRecords( 'postType', 'your_custom_post_type')

To get custom posts with specific category

getEntityRecords( 'postType', 'your_custom_post_type', category: [1,2,3])

To get custom posts with terms of custom taxonomy (I think is the specific answer to your question):

getEntityRecords( 'postType', 'your_custom_post_type', your_taxonomy: [1,2,3])

To get terms for your custom taxonomy:

getEntityRecords( 'taxonomy', 'your_taxonomy')
Lilongwe answered 1/10, 2019 at 10:39 Comment(0)
A
1

Ok, I've found the solution. All what I did was register taxonomy arguments.

add_filter('register_taxonomy_args', 'my_function', 10, 2);

function my_function ($args, $taxonomy)
{
    if ( in_array( $taxonomy, array('taxonomy1', 'taxonomy2' ) ) )
    {
        $args['show_in_rest'] = true;
    }
    
    return $args;       
}

And then I've used:

getEntityRecords( 'postType', 'post', {per_page: 3, taxonomy1: [1,2,3] } )
Asuncionasunder answered 11/1, 2020 at 23:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.