Skip to content

Instantly share code, notes, and snippets.

@ckanitz
Created April 15, 2025 09:47
Show Gist options
  • Save ckanitz/f872af9a0d984bc5102833f436c38389 to your computer and use it in GitHub Desktop.
Save ckanitz/f872af9a0d984bc5102833f436c38389 to your computer and use it in GitHub Desktop.
usePrimaryTerm(taxonomy, fallbackTermId)
/**
* WordPress dependencies.
*/
import { useEntityRecord } from '@wordpress/core-data';
import { useEffect, useRef, useState } from '@wordpress/element';
const { MutationObserver } = window;
export default function usePrimaryTerm(taxonomy, fallbackTermId) {
const termRef = useRef(
document.querySelector(`#yoast-wpseo-primary-${taxonomy}`)
);
const [termId, setTermId] = useState(
parseInt(termRef?.current?.value ?? fallbackTermId ?? 0)
);
const termEntity = useEntityRecord('taxonomy', taxonomy, termId);
useEffect(() => {
const handleValueChange = (mutationsList) => {
for (const mutation of mutationsList) {
if (
mutation.type === 'attributes' &&
mutation.attributeName === 'value'
) {
setTermId(parseInt(mutation.target.value));
}
}
};
const observer = new MutationObserver(handleValueChange);
if (termRef.current) {
observer.observe(termRef.current, {
attributes: true,
attributeFilter: ['value'],
});
}
return () => {
observer.disconnect();
};
}, []);
return termEntity;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment