Dynamically Create Terms in Taxonomy when Custom Post Type is Published. Almost There!

I’m trying to automatically create terms in a certain taxonomy when a certain custom post type is published. The newly created term must be the name of the post that was published.

Example: I have a custom post type “country” and a custom taxonomy “country_taxo”. When I publish a country say “Kenya” I want a the term “Kenya” to be automatically created under the “country_taxo” taxonomy.

I have accomplished this using the “publish_(custom_post_type) action hook”, but i can only get it to work statically. Example:

// This snippet adds the term "Kenya" to "country_taxo" taxonomy whenever 
// a country custom post type is published.

add_action('publish_country', 'add_country_term');
function add_country_term() {
    wp_insert_term( 'Keyna', 'country_taxo');
}

Like I mentioned above I need this to dynamically add the post title as the term. I tried this, but it doesn’t work:

add_action('publish_country', 'add_country_term');
function add_country_term($post_ID) {
    global $wpdb;
    $country_post_name = $post->post_name;
    wp_insert_term( $country_post_name, 'country_taxo');
}

Does anyone know how I would go about doing this? Any help is greatly appreciated.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You’re almost there – the problem is you’re trying to access the $post object when the function only receives the post ID.

add_action( 'publish_country', 'add_country_term' );
function add_country_term( $post_ID ) {
    $post = get_post( $post_ID ); // get post object
    wp_insert_term( $post->post_title, 'country_taxo' );
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x