I have some information stored in post meta that I'd like to convert to terms. I'd like to create a term in a custom taxonomy for every meta value with a particular key.
I need to loop through ALL posts, gathering all values of the metavalue key.
I'm thinking the code will be like this, I'm just not sure the syntax exactly.
<?php
$all_posts_with_release_year = new WP_Query( [
'post_type' => 'release'
] );
if ( $all_posts_with_release_year->have_posts() ) {
while ( $all_posts_with_release_year->have_posts() ) {
$all_posts_with_release_year->the_post();
$post_id = get_the_ID();
$release_year_value = get_post_meta( $post_id, 'wpcf-release-year', true );
//Check to see if a taxonomy term with that name exists.
if ($release_year_value exists as $taxonomy_term){
select $taxonomy_term for $post_id;
}else{
create $taxonomy_term with $release_year_value;
select $taxonomy_term for $post_id;
}
}
}
EDIT: I realize I have two smaller questions.
- How to create a taxonomy term in a foreach loop
- How to select a taxonomy term for a post in a foreach loop
I'm going to see about the answers to these on the site and will post an answer if I find it, so that someone who hasn't broken this bigger question down into the smaller ones yet can find help.
Thanks so much!
get_field
is an ACF function not a WordPress function, if you're using ACF to store that data then you'll need to mention that ( and it might make your question offtopic ). There are also several smaller questions inside this such as how to create taxonomy terms in code etc that have already been asked and answered on the site. Look those up and you might not need to ask this question. Likewise how to assign a term to a post in code, all of these have questions that have been answered already by other peopleget_field
. I'm not using ACF to store that. Thanks, I'll work through this and maybe can give my own solution to help others. Thanks Tom.get_post_meta
,get_metadata
is a lower level function,get_metadata( 'release'
is equivalent to creating aget_release_meta
for awp_release
table. I've adjusted your pseudocode accordingly