How best to store data (URLs and IDs) extracted from posts and pages using custom taxonomies
-
14-03-2021 - |
Question
I want to store metadata extracted from post/page content:
- IDs of other posts/pages on the same blog linked within the content of each post/page
- certain external URLs contained within the content of each post/page
I've created two custom taxonomies to store this information: internal_reference
and external_reference
. Both are non-hierarchical and non-public. Edit page meta-boxes are also switched off as the metadata is extracted programmatically, and I don't want users overriding this with the checkboxes provided for other taxonomies like categories.
I've written a function that can extract the IDs and URLs from the post/page content, which runs on the save_post
hook.
The problem I'm having is how best to store this information. Clearly I must use wp_set_post_terms
to associated the terms with the post in question, but I can't work out whether I need to use add_term_meta
to set the IDs and URLs or if I can just use the term's name or slug field. If it's best to store this using term meta data, then how do I find out each newly created term's ID after I call wp_set_post_terms
with a bunch of URLs or post IDs?
How is this sort of thing intended to be done in WordPress? Forgive me if this is a rather basic question, but this feature of WordPress is new to me.
Solution
Ah, I found it. I just need to give a unique name to each term (so for the external URLs, I named them url-[md5]
where [md5]
is the MD5 hash of the URL), and then call add_term_meta
and set the necessary information, then add this term to the post using my custom taxonomies. For example, this is the working external term metadata setter:
foreach ( $external_urls as $url ) {
$url = esc_url( $url );
// don't use wp_hash here because it salts the data
$term_name = "url-" . md5( $url );
$terms[$term_name] = $url;
}
// update post's reference taxonomy terms (replaces any existing terms)
wp_set_post_terms( $post->ID, array_keys( $terms ), 'external_reference' );
// add metadata
foreach ( $terms as $term_name => $url ) {
// get term
$term = get_term_by( 'name', $term_name, 'external_reference' );
// add URL as metadata for the term created above
update_term_meta( $term->term_id, "url", $url );
}