Created
April 15, 2025 09:47
-
-
Save ckanitz/f872af9a0d984bc5102833f436c38389 to your computer and use it in GitHub Desktop.
usePrimaryTerm(taxonomy, fallbackTermId)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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