baerkins
2/2/2018 - 7:12 PM

Auto-generate a taxonomy term when a post is created

Auto-generate a taxonomy term when a post is created

<?php

/**
 * Auto Gen Project Agency Taxonomy when an agency is created
 * @link https://gist.githubusercontent.com/brenna/7377802/raw/a5092e5b4bd2a094a6534d73e9f2f81f26783744/wp-autopopulate-taxonomy
 * 
 */
function FS__Update_Project_Agency_Terms($post_id) {
  
  // Only update terms if it's the post type we want
  if ( 'agencies' != get_post_type($post_id)) {
    return;
  }
  
  // Don't create or update terms for system generated posts
  if (get_post_status($post_id) == 'auto-draft') {
    return;
  }

  $tax        = 'project_agency';
  $meta_field = 'agency_post_id';
      
  /*
  * Grab the post title and slug to use as the new 
  * or updated term name and slug
  */
  $term_title = get_the_title($post_id);
  $term_slug  = get_post( $post_id )->post_name;
  
  /*
  * Check if a corresponding term already exists by comparing 
  * the post ID to all existing terms `agency_post_id` meta field
  */
  $existing_terms = get_terms($tax, [
    'hide_empty' => false
  ]);
  
  foreach($existing_terms as $term) {
    $agency_id = get_term_meta($term->term_id, $meta_field, true);
    if ($agency_id == $post_id) {
      //term already exists, so update it and be done
      wp_update_term($term->term_id, $tax, [
        'name' => $term_title,
        'slug' => $term_slug
      ]);
      return;
    }
  }
  
  /* 
  * If we didn't find a match above, this is a new post, 
  * so create a new term. If success, then add the term
  * ID as meta field.
  */
  $term = wp_insert_term($term_title, $tax, [
    'slug' => $term_slug
  ]);

  if ( ! is_wp_error( $term ) ) {
    $term_id = isset( $term['term_id'] ) ? $term['term_id'] : 0;
    if ( $term_id ) {
      add_term_meta ($term_id, $meta_field, $post_id);
    }
  }
}
  
add_action('save_post', 'FS__Update_Project_Agency_Terms');