Support

Account

Home Forums General Issues Adding taxonomies to attachments

Solved

Adding taxonomies to attachments

  • Good evening folks,

    For the needs of my portfolio, I’ve built a set of custom fields that only display for attachments. Those fields are like filename, reference, version_name, description, category, rating, city, state_province, country, copyright, date_of_shooting, max_available_width, max_available_height.
    As you can see read, I’ve a category field, which is set in ACF as a Taxonomy.

    Since I’m updating from my old code, I’ve hundreds of attachments I need to update (I’ve done previous posts about this here). Thanks to James and John, I’ve been able to manage how to use update_field($fieldKey, $value, $attachmentID); (among others) and it’s working perfectly for everything but the Taxonomy.
    I don’t know how to prepare my $value to make it work.

    My actual imported format is like so 'category' => 'Wildlife,Urban'
    I’ve already created all the needed taxonomies as categories in WordPress, those are a subcategory from the category “Portfolio”.
    Note these categories also exist as translated, using WPML.

    Thanks in advance for you help.

  • ACF stores the values of a taxonomy field as an array of term ID values.

    So you’ve basically got to get the current category, split it on the commas and then get the correct term ID and put them in an array. See get_term_by() https://codex.wordpress.org/Function_Reference/get_term_by

    
    $list = split(',', $current_category);
    $categories = array();
    foreach ($list as $name) {
      $term = get_term_by('name', $name, $your_taxonomy);
      $categories[] = $term->term_id;
    }
    update_field($fieldKey, $categories, $attachmentID);
    
  • Brillant!
    Thanks John.

Viewing 3 posts - 1 through 3 (of 3 total)

The topic ‘Adding taxonomies to attachments’ is closed to new replies.