Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
PHP | Comma seperated string into ACF compatible multidimensional array
<?php
$string = "Skateboarding, Surfing, Horseriding"; // The original comma seperated string
$columns = explode(", ", $string); // Turns the string into an array
$column_array = array(); // Sets up the outer array
foreach ($columns as $key => $value) {
// Loops through the array creating keys and values
$column_array[$key]['skill'] = $value;
// $column_array[$key]['level'] = '0';
}
// As a function
function string_to_repeater($string, $separator) {
$columns = explode($separator, $string); // Turns the string into an array
$column_array = array(); // Sets up the outer array
foreach ($columns as $key => $value) {
// Loops through the array creating keys and values
$column_array[$key]['skill'] = $value;
// $column_array[$key]['level'] = '0';
}
return $column_array;
}
@morgyface

This comment has been minimized.

Copy link
Owner Author

@morgyface morgyface commented May 6, 2020

String to ACF Repeater

I had a problem, an API delivered data as WordPress custom fields. Most of the fields were text only 👍, however in situations where there were multiple values, it would be delivered as a comma separated string 👎.

Following import using the API plugin, I wanted my client to be able to edit the data so I needed to set-up ACF fields in a way that made them compatible. That way once the data was in place the client could edit the post and the associated meta values.

The problem was; no ACF field type stores data as a comma separated string, so I needed to transform the strings into a compatible format.

The solution is above as both code and a function. It essentially turns a string list into a repeater. Notice the commented out line $column_array[$key]['level'] = '0'; which would, in effect, add an additional sub field called level with a value of 0. That way the user could add further data to the list.

This is really useful to me. Probably not to anyone else, if it is, add a comment, it'd be good to know it's helped others! 🤙

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment