Select posts that have a specific term using withSelect in Gutenberg block

Viewed 1192

I'm trying to select posts -- or more specifically, a custom post type -- that belong to a specific term, and display them in my Gutenberg block's edit screen. I'm wanting to recreate what would be tax_query with WP_Query, but in Javascript.

I'm able to select posts, but I'm unsure what parameters to use with getEntityRecords to select by term (or if it is even possible). The documentation is still a little vague at this point.

Here's where I'm at. This successfully selects all posts of the 'rmenu' type:

const items = select("core").getEntityRecords(
    "postType",
    "rmenu"
);

Does anyone know if getEntityRecords is the right way to handle this?

Thanks.

2 Answers

Although Capi's answer is correct, it wasn't clear for me that this would also work for custom taxonomies. It turns out wp.data will add your custom taxonomies automatically as properties to the post object. For example, a post could look like this:

{
    title: "hello world",
    content: "this is a post",
    id: 123,
    type: 'my-custom-posttype'
    my-custom-tax: [5, 8, 24],
    ...
}

So, in order to get all the posts of the type my-custom-posttype that have a term with ID 4 or 8 of the taxonomy my-custom-tax, you would run this query:

wp.data.select( 'core' ).getEntityRecords( 'postType', 'my-custom-posttype', { 'my-custom-tax':[4,8] })

Important! If you test this in your browser, you need to run it twice. The first time it will return an empty array, because it only invokes the promise.

Related