@wordpress/block-library
Version:
Block library for the WordPress editor.
63 lines (62 loc) • 2.54 kB
JavaScript
;
Object.defineProperties(exports, {
__esModule: { value: true },
[Symbol.toStringTag]: { value: "Module" }
});
let _wordpress_core_data = require("@wordpress/core-data");
let _wordpress_data = require("@wordpress/data");
// packages/block-library/src/term-name/use-term-name.js
/**
* Hook to fetch term name 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 useTermName(termId, taxonomy) {
const contextBasedTerm = (0, _wordpress_data.useSelect)((select) => {
if (!termId || !taxonomy) return null;
return select(_wordpress_core_data.store).getEntityRecord("taxonomy", taxonomy, termId);
}, [termId, taxonomy]);
const templateBasedTerm = useTemplateBasedTermData();
const hasContext = Boolean(termId && taxonomy);
return {
hasContext,
term: hasContext ? contextBasedTerm : templateBasedTerm
};
}
/**
* Fallback hook to fetch term data from template context.
* Parses the template slug to determine if we're on a specific term archive.
*/
function useTemplateBasedTermData() {
const taxonomyMatches = (0, _wordpress_data.useSelect)((select) => {
const { getCurrentPostId, getCurrentPostType, getCurrentTemplateId } = select("core/editor");
const currentPostType = getCurrentPostType();
const templateId = getCurrentTemplateId() || (currentPostType === "wp_template" ? getCurrentPostId() : null);
return templateId ? select(_wordpress_core_data.store).getEditedEntityRecord("postType", "wp_template", templateId)?.slug : null;
}, [])?.match(/^(category|tag|taxonomy-([^-]+))$|^(((category|tag)|taxonomy-([^-]+))-(.+))$/);
let taxonomy;
let termSlug;
if (taxonomyMatches) {
if (taxonomyMatches[3]) {
taxonomy = taxonomyMatches[6] ? taxonomyMatches[6] : taxonomyMatches[4];
termSlug = taxonomyMatches[7];
}
taxonomy = taxonomy === "tag" ? "post_tag" : taxonomy;
}
return (0, _wordpress_data.useSelect)((select) => {
if (!taxonomy || !termSlug) return null;
const { getEntityRecords } = select(_wordpress_core_data.store);
const termRecords = getEntityRecords("taxonomy", taxonomy, {
slug: termSlug,
per_page: 1
});
if (termRecords && termRecords[0]) return termRecords[0];
return null;
}, [taxonomy, termSlug]);
}
exports.useTermName = useTermName;
//# sourceMappingURL=use-term-name.cjs.map