UNPKG

@wordpress/block-library

Version:
57 lines (56 loc) • 2.35 kB
import { store, useEntityProp } from "@wordpress/core-data"; import { useSelect } from "@wordpress/data"; // packages/block-library/src/term-count/use-term-count.js /** * Hook to fetch term count based on context or fallback to template parsing. * * This hook prioritizes context-provided termId and taxonomy, but falls back to * template-based detection when no context is available. * * @param {string|number} termId The term ID from context * @param {string} taxonomy The taxonomy name from context */ function useTermCount(termId, taxonomy) { const [count] = useEntityProp("taxonomy", taxonomy, "count", termId); const templateBasedData = useTemplateBasedTermData(); const hasContext = Boolean(termId && taxonomy); return { hasContext, termCount: hasContext ? count || "" : templateBasedData }; } /** * Fallback hook to fetch term data from template context (backward compatibility). * This maintains the same logic as the original implementation for cases where * no termId/taxonomy context is provided. */ function useTemplateBasedTermData() { const taxonomyMatches = useSelect((select) => { const { getCurrentPostId, getCurrentPostType, getCurrentTemplateId } = select("core/editor"); const currentPostType = getCurrentPostType(); const templateId = getCurrentTemplateId() || (currentPostType === "wp_template" ? getCurrentPostId() : null); return templateId ? select(store).getEditedEntityRecord("postType", "wp_template", templateId)?.slug : null; }, [])?.match(/^(category|tag|taxonomy-([^-]+))$|^(((category|tag)|taxonomy-([^-]+))-(.+))$/); let taxonomy; let termSlug; if (taxonomyMatches) { if (taxonomyMatches[1]) taxonomy = taxonomyMatches[2] ? taxonomyMatches[2] : taxonomyMatches[1]; else if (taxonomyMatches[3]) { taxonomy = taxonomyMatches[6] ? taxonomyMatches[6] : taxonomyMatches[4]; termSlug = taxonomyMatches[7]; } taxonomy = taxonomy === "tag" ? "post_tag" : taxonomy; } return useSelect((select) => { if (!taxonomy || !termSlug) return ""; const { getEntityRecords } = select(store); const termRecords = getEntityRecords("taxonomy", taxonomy, { slug: termSlug, per_page: 1 }); if (termRecords && termRecords[0]) return termRecords[0].count || ""; return ""; }, [taxonomy, termSlug]); } export { useTermCount }; //# sourceMappingURL=use-term-count.mjs.map