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.
You’re almost there – the problem is you’re trying to access the
$post
object when the function only receives the post ID.