Advanced Custom Fields – update_sub_field() for repeater fields
I’ve been working on a WordPress web design project using a hand made front-end form to update an Advanced Custom Fields repeater field via AJAX. This was a bit of a stretch for me as I’ve never used AJAX before and I hit a wall when 99% there!
I hit a snag with the update_sub_field() function to target the right repeater row and field to update. There were two issues – one is that the rows don’t start from 0 like I expected and there’s a functions.php snippet to fix that (bottom of this page).
The second was that the documentation was a bit ambiguous in describing how the data needs to be sent to the back end (for someone unfamiliar with arrays, like me), with this example being given:
// target a nested sub field directly. update_sub_field( array('repeater', 1, 'sub_repeater', 2, 'sub_sub_field'), 'This value is for repeater row 1, and sub_repeater row 2!' );
I replicated this with my incoming data from the AJAX function but it wouldn’t update unless I hard coded it in the update_sub_field() PHP function. I thought the data was exactly the same, but it actually wasn’t – it had quote marks around it so was being treated like a string rather than converted to an array.
ACF support suggested making sure the array was sent back correctly and a developer friend fixed this quickly by exploding the query string into an array before passing it to update_sub_field()
Part of my PHP function that the AJAX call sends data back to:
$post_id = $_POST['post-id']; $memberName = $_POST['member-name']; $acfPath = $_POST['acf-path']; // Convert the query string to array - thanks Ewan! $combined = explode(",", $acfPath); // Now sending $combined instead of the raw query string in $acfPath update_sub_field($combined, $memberName, $post_id);
So that fixed things and I hope this quick blog helps anyone else struggling with update_sub_field() updating the Repeater field in Advanced Custom Fields