Home Forums General Issues Copy taxonomy values to a custom fields


Copy taxonomy values to a custom fields

  • Hi,
    I’m trying to copy the value of a taxonomy named item_year to the newly created custom field named year for each of my posts. Notice that year doesn’t have anything to do with the “real” year of the post creation, it’s just a meta description.
    Do you think that there’s an automatic way to do that without going over all my posts and manually copying the value of each item_year for the custom field?

    I found a script that does similar thing with other plugin, do you think it can be modified to work with ACF as well?

    Thanks a lot!

  • Yes, something like that could work, but it depends on how many posts you have.

    add_action('acf/init', 'update_post_year_field');
    update_post_year_field() {
      $args = array(
        'post_type' => 'your-post-type',
        'post_status' =>'any',
        'posts_per_page' => -1,
        'meta_query' => array(
          'relation' => 'OR',
            'key' => 'year'
            'compare' =>'NOT EXISTS'
            'key' => 'year'
            'value' => '',
            'compare' =>'='
      $query = new WP_Query($args);
      if (count($query->posts)) {
        foreach ($query->posts as $post) {
          $terms = wp_get_post_terms($post->ID, 'your-taxonomy');
          if (!empty($terms)) {
            // use the field key here, not the field name
            update_field('field_key', get_field('item_year', $term[0]), $post->ID);

    If you have a lot of posts it may timeout the loading of your site. This is why the query is looking for the field not being set or has an empty value. The number of posts returned should be reduced each time and eventually it will complete and then you can remove the filter.

    But you will also need to create an acf/save_post filter to update this field when a new post is created or a post is updated.

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

You must be logged in to reply to this topic.