Advanced Custom Fields – quick hack to move a field to another group

By 25th November 2012Development
Advanced Custom Fields - quick hack to move a field to another group

I was just in a situation where I had an ACF group with 21 fields in it … the first was a repeater with images that had already been populated, the other twenty were new fields that I’d just painstakingly added … and I realised it would be better to put them into two groups, the repeater in one and all the others in a new one.

What to do? I could quickly create a new group and create a new repeater there, but then I’d have to re insert that data … or I could recreate the other twenty fields in the new group. Both options frankly suck, so this seemed like a perfect time to get into how ACF stores its data and hack at the database to move the fields rather than delete and recreate. It’s pretty easy once you know where to look.

First a quick look at the plugin source code to get an idea of where it puts its data. I opened the acf.php file and had a quick scan through, finding the get_field_groups() function, where there is this code:

// get acf's<br />$result = get_posts(array(<br /> 'numberposts' => -1,<br /> 'post_type' => 'acf',<br /> 'orderby' => 'menu_order title',<br /> 'order' => 'asc',<br /> 'suppress_filters' => false,<br /> ));

The field groups are stored as posts, with post_type of “acf”, so you can run this SQL to see them:

SELECT * FROM `wp_posts`<br />WHERE post_type="acf"

Back in WP admin I created a new, empty field group – what I’ll do is move the repeater into it, and leave the twenty fields where they are. Running that SQL shows me the original group and the new one. Take a note of the row IDs.

Now back to the code … next function is get_acf_fields – this takes the $post_id which points to the field group, and it reads from the WP postmeta table:

$rows = $wpdb->get_results( $wpdb->prepare(<br /> "SELECT meta_key FROM $wpdb->postmeta " .<br /> "WHERE post_id = %d AND meta_key LIKE %s", <br /> $post_id, 'field_%'), ARRAY_A);

I’ve got the ID of 4543 for the field group that contains the repeater field that I want to move, so this shows me the fields in that group:

SELECT * FROM `wp_postmeta`<br />WHERE meta_key LIKE "field_%"<br />AND post_id=4543

The filter meta_key LIKE “field_%” helps to restrict the postmeta records to just those related to ACF. Look through the meta_value values in that list to find the repeater, and change the post_id to the group you want to move it into.

That’s it!

Now check back in WP Admin and if you’ve been following along with your own data, inspect your field groups and you should see that the repeater field has moved, and if you check the page that was using that field it should still work as before.