0

I have a custom post type called "Country Story". The title of which will be the name of the country. I want Wordpress to automatically create a new taxonomy called "country" of the same name, i.e. a Country Story called Thailand is created, so I want WP to create a Country taxonomy called Thailand as well. The Country taxonomy already setup. I have the code below so far. It does what I want except I don't know how to get the title during the action hook for publishing the post to pass on to the $cat variable. Can anyone help?

function add_country_category_automatically($post_ID) {
global $wpdb;
if(!has_term('','country',$post_ID)){
    $cat = "get title of Country Story published to pass on to Country category";
    wp_set_object_terms($post_ID, $cat, 'country');
}
}
add_action('publish_country-story', 'add_country_category_automatically');

2 Answers 2

3

Can you not just call get_the_title() to get the title of the Country Story?

$cat = get_the_title($post_ID);
2
  • Yes that worked, thank you! I should have tried that but for some reason I was thinking it would be something more complicated.
    – user716816
    Commented Aug 20, 2011 at 2:00
  • Awesome! Could you accept the answer so we knows it's solved? Commented Aug 23, 2011 at 19:15
1

Pretty clever solution, i've been searching about 2 days for this. user716816 you might have figured this out already but while your code creates a new term for the given taxonomy when the post is created, it also assigns the new taxonomy term to the new post. If you add another wp_set_object_terms but this time with NULL it will remove the newly created term from the post but keep the term as you initially intended. Anyway i see this post is since 2011 but i thought it would be helpful to share for others that might be looking on this:

function add_country_category_automatically($post_ID) {
global $wpdb;
if(!has_term('','country',$post_ID)){
    $cat = "get title of Country Story published to pass on to Country category";
    wp_set_object_terms($post_ID, $cat, 'country');
    wp_set_object_terms($post_ID, NULL, 'country');
}
}
add_action('publish_country-story', 'add_country_category_automatically');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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