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

The question:

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.

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

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

Leave a Comment