'Wordpress dynamic block: get posts from post taxonomies and custom post type taxonomies
I want to get posts of selected post type (post, event), then choose a taxonomy, and finally select a category. I have three select fields in my block for each: post type, taxonomy, category.
After that I'm creating a call to wp.data object to get posts. For custom post type this works fine:
wp.data.select('core').getEntityRecords('postType', 'event', {event_category: [70]})
wp.data.select('core').getEntityRecords('postType', 'event', {event_localization: [200]})
But for the default "post" post type I need to change query parameter to:
for category (because taxonomy type returns 'category' i can't put it dynamically, i need to change it to 'categories'):
wp.data.select('core').getEntityRecords('postType', 'post', {categories: [2]})
and for tags (returned taxonomy 'post_tag', need to change to 'tags'):
wp.data.select('core').getEntityRecords('postType', 'post', {tags: [7]})
I managed to make it work right, but is there a better solution for this than if-else and check taxonomy type, or we can make it work without if-else using query in getEntityRecords ?
export default withSelect(
(select, props) => {
const { attributes } = props;
const { numberOfPosts, postType, postsTaxonomy, postsCategory } = attributes;
let query = { per_page: numberOfPosts }
// query for categories
if (postsCategory && postsTaxonomy === 'category') {
query['categories'] = [postsCategory];
}
//query for tags
else if (postsCategory && postsTaxonomy === 'post_tag') {
query['tags'] = [postsCategory];
}
// query for custom post type taxonomies
else if (postsCategory) {
query[postsTaxonomy] = [postsCategory];
}
return {
posts: select('core').getEntityRecords('postType', postType, query)
}
}
)(Edit); ```
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
