0

I have a hierarchical custom taxonomy called "locations". The parent categories are country names, the child categories are the territories under the country.

How can i attach these terms to a post programatically?

$country = 'Egypt';
$territory = 'Hurghada';

So, if the Egypt category doesn't exist, i need to create it, and i need to attach the $territory in a subcategory under Egypt.

This is where i am so far:

$post_id = 10;

$country_term_id = term_exists( $country, 'locations' );

if ($country_term_id !== 0 && $country_term_id !== null) {
    wp_set_post_terms($id, $country,'locations');
} else {
    //I guess this is where i need to set the territory?
} 
2

Since wp_set_post_terms() does not accept hierarchy for it, you will first have to check if terms exist already, create them using wp_insert_term() if not and only then assign to post.

Note that there had been (don't know current state) some cache related bugs with doing such things on the fly, see Inserting terms in an Hierarchical Taxonomy

  • Thanks, yes, i know understand the logic, i just need to check & create the subcategory with wp_insert_term, and i just attach the term by id to the post – passatgt May 17 '13 at 13:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.