Thank you for waiting and on my test website, I was able to make this work for the front-end forms as well as the back-end post edit screen.
Note: Please make sure to keep the "state" custom field as discussed in the previous ticket, because it is easier to populate the state value in it, using the script. The value from that field is then used in the custom code for the processing of the taxonomy term assignment.
The following function executes when the post is saved (from front-end and back-end) and attaches the term with the same name in the taxonomy named "State":
add_action( 'save_post', 'custom_process_state_save_post', 10,3 );
function custom_process_state_save_post( $post_id, $post, $update ) {
// exit if not the target post type
if ( ('post' !== $post->post_type) OR ($post->post_status == 'auto-draft') OR (empty($_POST)) ) {
return;
}
// current post ID
$post_id = $post->ID;
// target taxonomy slug
$taxonomy_slug = 'state';
// $_POST['wpcf-state'] value exists, it means that post is being added using the front-end form
if(!empty($_POST['wpcf-state'])) {
// get the term's name from the form's state field
$term_name = $_POST['wpcf-state'];
// call the function that processes the taxonomy attachment
custom_process_new_state_term($post_id, $term_name, $taxonomy_slug);
}
// $_POST['wpcf']['state'] value exists, it means that post is being added using the back-end post edit screen
if(!empty($_POST['wpcf']['state'])) {
// get the term's name from the state field
$term_name = $_POST['wpcf']['state'];
// call the function that processes the taxonomy attachment
custom_process_new_state_term($post_id, $term_name, $taxonomy_slug);
}
}
// function that processes the taxonomy attachment
function custom_process_new_state_term($post_id, $term_name, $taxonomy_slug) {
// check if the term already exists
$term = term_exists( $term_name, $taxonomy_slug );
// if does exist
if ( $term !== 0 && $term !== null ) {
// attach it to the current post
wp_set_post_terms( $post_id, $term['term_id'], $taxonomy_slug );
}
// if doesn't exist
else
{
// first add it as a new term in the taxonomy
$inset_new_term = wp_insert_term($term_name, $taxonomy_slug);
if ( ! is_wp_error( $inset_new_term ) )
{
// and then attach this new term to the current post
$term_id = $inset_new_term['term_id'];
wp_set_post_terms( $post_id, $term_id, $taxonomy_slug );
}
}
}
Note: in this example, the target post type which includes this custom field and taxonomy is "post", taxonomy slug is "state" and the custom field slug is "state". Be sure to update these values, as per your website.
The custom code examples from our forum are shared to get you started in the right direction. You're welcome to adjust them as needed and for more personalized customization assistance, you can consider hiring a professional from our list of recommended contractors:
https://toolset.com/contractors/