hooks.js
74 lines
| 1 | const { useSelect } = wp.data; |
| 2 | |
| 3 | export const usePostTypes = () => { |
| 4 | return useSelect(select => { |
| 5 | return select("core").getPostTypes({ per_page: -1 }) || []; |
| 6 | }, []); |
| 7 | }; |
| 8 | |
| 9 | export const usePostType = postType => { |
| 10 | return useSelect( |
| 11 | select => { |
| 12 | return select("core").getPostType(postType) || {}; |
| 13 | }, |
| 14 | [postType] |
| 15 | ); |
| 16 | }; |
| 17 | |
| 18 | export const useTaxonomies = () => { |
| 19 | return useSelect(select => { |
| 20 | return select("core").getTaxonomies({ per_page: -1 }) || []; |
| 21 | }, []); |
| 22 | }; |
| 23 | |
| 24 | export const usePostTypeTaxonomies = postType => { |
| 25 | return useSelect( |
| 26 | select => { |
| 27 | return (select("core").getTaxonomies() || []).filter(taxonomy => { |
| 28 | const postTypeTaxonomies = postType.taxonomies || []; |
| 29 | return postTypeTaxonomies.includes(taxonomy.slug); |
| 30 | }); |
| 31 | }, |
| 32 | [postType] |
| 33 | ); |
| 34 | }; |
| 35 | |
| 36 | export const useTermsGroupbyTaxnomy = taxonomies => { |
| 37 | return useSelect( |
| 38 | select => { |
| 39 | const obj = {}; |
| 40 | for (const taxonomy of taxonomies) { |
| 41 | obj[taxonomy.rest_base] = |
| 42 | select("core").getEntityRecords("taxonomy", taxonomy.slug, { |
| 43 | per_page: -1 |
| 44 | }) || []; |
| 45 | } |
| 46 | return obj; |
| 47 | }, |
| 48 | [taxonomies] |
| 49 | ); |
| 50 | }; |
| 51 | |
| 52 | export const usePosts = (postType, query) => { |
| 53 | return useSelect( |
| 54 | select => { |
| 55 | return ( |
| 56 | select("core").getEntityRecords("postType", postType.slug, query) || [] |
| 57 | ); |
| 58 | }, |
| 59 | [postType, query] |
| 60 | ); |
| 61 | }; |
| 62 | |
| 63 | export const useCurrentPostId = () => { |
| 64 | return useSelect(select => { |
| 65 | return select("core/editor").getCurrentPostId(); |
| 66 | }); |
| 67 | }; |
| 68 | |
| 69 | export const useCurrentPostType = () => { |
| 70 | return useSelect(select => { |
| 71 | return select("core/editor").getCurrentPostType(); |
| 72 | }); |
| 73 | }; |
| 74 |