WordPress – Track Creator (Author) of Taxonomy Terms


About The Author
Cabe Nolan is the founder of WP Cover where he shares his insight into WordPress, development, & entrepreneurship. Outside of WPCover, Cabe continues to run a successful WordPress development firm, Bold City Design as well as a few high profile websites, Arrivala, Two Way Resume, Dock Skipper, and a successful outdoors brand, DolfinPack.







WordPress – Track Creator (Author) of Taxonomy Terms

Recently a client approached us with the issue of tracking the creator or author of individual custom taxonomy terms. They had a lot of team members working on the site and they noticed many terms were being inputted incorrectly. Each term had a lot of custom fields that needed to be filled out to create the complex taxonomy pages. Unlike post types, taxonomies do not track the creating author or maintain different revisions. Therefore, some custom functionality needed to be created.

To achieve this, we leveraged the Advanced Custom Fields plugin to create a new field group associated with the taxonomy. Within that field group, we created an individual field called ‘term_author’. Now it’s time to open up that functions.php file within your active theme and write a function that will populate that custom field upon term creation. Here it is:

function wpcover_save_user($term_id, $tt_id, $taxonomy) {
   $term = get_term($term_id, $taxonomy);
   $current_user = wp_get_current_user();
   $email = $current_user->user_email;
   $thetax = 'location_' . $term->term_id;
   if(!get_field('term_author', $thetax)) {
   	update_field('term_author', $email, $thetax);
   }
}
add_action( 'edit_term', 'wpcover_save_user', 10, 3 );

That’s all there is to it! This will save the email address of the user that created the term to the ACF custom field. I would also recommend making this field READONLY, which can be accomplished following our tutorial on making Advanced Custom Fields Readonly.

Alternative

As an alternative to the above code, you could also make it so the last user to edit the taxonomy term is saved in the field. This would be a simple change by eliminating the if statement. Example:

function wpcover_save_user($term_id, $tt_id, $taxonomy) {
   $term = get_term($term_id, $taxonomy);
   $current_user = wp_get_current_user();
   $email = $current_user->user_email;
   $thetax = 'location_' . $term->term_id;
   update_field('term_author', $email, $thetax);
}
add_action( 'edit_term', 'wpcover_save_user', 10, 3 );

ENJOY!


Share Your Thoughts

Leave a Reply

Your email address will not be published.


Related Stuff You Might Like







WordPress News, Tips, & Code Snippets

Join the WP Cover mailing list and get wordpress news, tips, code snippets, security warnings, and more delivered right to your inbox.  We won't flood your inbox, newsletters typically go out every 1-2 weeks unless it involves an important security release.

You have Successfully Subscribed!