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

时间:2019-01-09 22:03:48

标签: wordpress wordpress-gutenberg

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 个答案:

答案 0 :(得分:0)

getEntityRecords的第三个参数是query对象。您可以传递any query argument accepted by Wordpress API,例如categoriestags。按类别字词选择如下所示:

const items = select("core").getEntityRecords(
  "postType",
  "rmenu",
  { categories: [ 13 ] }
}

答案 1 :(得分:0)

尽管Capi的答案是正确的,但对我来说,这还不适用于自定义分类法。事实证明,wp.data会将您的自定义分类法自动添加为post对象的属性。例如,帖子可能看起来像这样:

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

因此,为了获取类型为my-custom-posttype或ID为48的{​​{1}}类型的所有帖子,您可以运行以下命令查询:

my-custom-tax

重要!!如果您在浏览器中对此进行了测试,则需要运行两次。第一次它将返回一个空数组,因为它仅调用promise。