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!
The post WordPress – Track Creator (Author) of Taxonomy Terms appeared first on WP Cover.