Support

Account

Home Forums General Issues Help converting an existing custom field into ACF? Reply To: Help converting an existing custom field into ACF?

  • For simple text based fields, just setting up the fields in ACF usually works. This includes text, textarea, number, url, email, password, radio, and single select type fields (although the number fields will return numbers as text, so that could be a problem).

    With other types of fields you need to also create the field key values in the database and the values stored in them need to match the values that ACF stores. For example, ACF stores a “1” or a “0” for true/false fields. If you where storing true and false using WP then the values in the database are being stored as serialized values representing true and false.

    If the values stored are exactly the same then you can get ACF to recognize and output the other types of fields by adding the field key to the database for each field. This can be somewhat problematic since you need to have an entry added for every post that has a value stored for it in the custom field.

    Here’s a simple script that can do this, although it could time out if you have a lot of posts to deal with (you could set this up as a cron). But again, this will only work if the type of data stored is the same as well. I would also make sure I backed up my database before trying it.

    
    // set up an array with all of the field names 
    // and field keys that you've created in ACF
    // this will not work on repeater or flex content fields and sub fields
    $fields = array(
      'field_name_1' => 'field_key_1',
      'field_name_2' => 'field_key_2',
      // etc...
    );
    // get every post
    $args = array(
      'post_type' => 'any',
      'post_status' => 'any',
      'posts_per_page' => -1
    )
    $query = new WP_Query($args);
    if (count($query->posts)) {
      foreach ($query->posts as $post) {
        $post_id = $post->ID;
        // get all post meta for the post can speed 
        // things up we can actually ignore $meta but 
        // calling this way forces WP to get all meta 
        // values for a post in one query
        $meta = get_post_meta($post_id);
        foreach ($fields as $field_name => $field_key) {
          $value = get_post_meta($post_id, $field_name, true);
          if ($value != '') {
            update_post_meta($post_id, '_'.$field_name, $field_key);
          }
        }
      }
    }
    

    there are probably other creative ways to do this. Would definitely be faster if you queried the database directly using $wpdb, but I’m not sure of the details on how to do that.