Problem: I have a Form used to create posts. There is a taxonomy field in the Form so Users can choose which term(s) to apply to the new post. I would like to display only terms that were created by the current logged-in User.
Solution: Since WordPress does not natively track the author of each term, you must programmatically add that term author ID in a custom field associated with each term when the term is created. Once that custom field value is added successfully, you can then use the get_terms hook to filter the terms available in the taxonomy field options. Here is an example of the code:
// RESTRICT TAXONOMY TERM FIELD OPTIONS TO USER'S OWN TERMS BY TERM FIELD VALUE
// https://toolset.com/forums/topic/show-only-terms-created-by-current-user-in-taxonomy-dropdown-on-the-form/
function tssupp_terms_by_current_user( $terms, $taxonomies, $args, $term_query ){
$pages = array( 123, 456 ); // comma-separated list of page IDs where this Form is displayed
$taxonomy_slug = 'tax-slug'; // slug of the taxonomy to filter
$author_field_slug = 'field-slug'; // slug of the post author id field
// you should not edit below this line
// loop over each term and get its custom field value
// compare that field value against the current user id and drop any terms with a different value
$user_id = get_current_user_id();
if ( is_page( $pages ) && $taxonomies[0] == $taxonomy_slug ) {
foreach($terms as $key=>$term) {
$term_author = get_term_meta($term->term_id, 'wpcf-' . $author_field_slug, true);
if( $term_author != $user_id ) {
unset( $terms[$key] );
}
}
}
return $terms;
}
add_filter( 'get_terms', 'tssupp_terms_by_current_user',10,4);