Support

Account

Home Forums General Issues Convert an ACF field to taxonomy

Helping

Convert an ACF field to taxonomy

  • My client has thousands of custom posts and wants to categorize them using custom field values.

    For example, he wants to categorize students according to the state. And there is already a field named state. Is there a way we can use that field to add each custom post into State taxonomy? Otherwise, it’ll take weeks to do it manually.

  • There is no easy way to do this. I do not know how the current field is saved but the taxonomy field stores values as a taxonomy ID, and categorizing by this I assume you mean you want to assign the terms to posts in the normal WP way. I can only give you an example. I am unable to give you all the code, a lot of what I am going to give you is just what you need to do.

    What I am going to give you is a temporary function that you put in functions PHP an run it by loading every page until you get the “completed” message and then you remove it.

    
    add_action('init', 'convert_field_to_terms');
    function convert_field_to_terms() {
      global $post;
      $args = array(
        'post_type' = 'your-post-type',
        'posts_per_page' => -1, // get all
        // get only posts that have not already been updated
        'meta_query' => array(
          'relation' =. 'OR',
          array(
            'key' => 'state_update_complete',
            'compare' => 'NOT EXISTS'
          ),
          array(
            'key' => 'state_update_complete',
            'value' => 0
          )
        )
      );
      $query = new WP_Query($args);
      if ($query->have_posts()) {
        while ($query->have_posts()) {
          $query->the_posts();
          // this is where you are going to need to figure out the details
    
          // get the ACF field value
          // ...
          // get the term that matches the ACF value or 
          // create the term if it does not exists
          // using get_term_by or insert_term()
          // ...
          // use wp_set_object_terms() to add terms to post
          // ...
          // set a meta value so we don't do this again if we need to run it multiple times
          update_post_meta($post->id, 'state_update_complete', '1');
        } // end while posts
      } // end if posts
    
      // the above loop will time out your site if there are a lot 
      // of posts that need to be updated
      // that means that anything after this point will only happen if
      // all posts are updated
      die('State Update Has Been Completed');
      // once you see the above message you can delete this action
    
    } // end function
    
Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.