How to assign taxonomy terms to created/edited posts

Created by Phil Kurth, Modified on Wed, 12 Oct, 2022 at 2:09 PM by Phil Kurth

When mapping taxonomy fields to a newly created or edited post, the terms aren't currently assigned to the post — only the ACF field is updated. This is a known issue that will be resolved but in the meantime, you can achieve the same result using the following snippet. Be sure to update all appropriate parts of this to suit your unique scn


// When a new post is created, run the callback function.
add_filter( 'af/form/editing/post_created', 'example_map_taxonomy_terms_to_post', 10, 3 );

// Note that you can also use the `af/form/editing/post_updated` hook to map taxonomy terms when a post is updated via a
// form as well.
//add_filter( 'af/form/editing/post_updated', 'example_map_taxonomy_terms_to_post', 10, 3 );

function example_map_taxonomy_terms_to_post( $post, $form, $args ) {
  // Only run on a specific form.
  if ( $form['key'] !== 'YOUR_FORM_KEY_HERE' ) {
    return;
  }

  // Assuming we have a field named 'categories' on the form. At this point, the post has already been created so
  // we can call on field values directly from the created post and use those to set the terms on the post.
  if ( $terms = get_field( 'categories', $post->ID ) ) {

    // If the field is set to return term objects, get the IDs. If the field returns an array of term IDs, we can
    // just use the $terms variable with wp_set_post_categories() and skip this step.
    $term_ids = [];
    foreach ( $terms as $cat ) {
      $term_ids[] = $cat->term_id;
    }

    // Save the terms of the desired category to the post.
    wp_set_post_terms( $post->ID, $term_ids, 'category' );
  }
}

Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select at least one of the reasons

Feedback sent

We appreciate your effort and will try to fix the article