Formatting an Address

By default an address field is rendered by adding every value on a newline. Something like:

Address 1

Obviously, this is very generic, and not always what you want. Let's rearrange it a bit to be more readable.


// This only works for single cell values, so disable separated fields. (or use the global setting)
add_filter('gfexcel_field_separated_address', '__return_false');

// Magically format address according to $format
add_filter('gfexcel_field_value_address', function ($original_value, $entry, $field) {
    $format = "[address_1]\n[city], [state] [zipcode]"; // Change this to whatever you want. Wrap every key with [].

    // Don't change anything below here. The keys here are the field names to replace. Dont even change the order!
    $map = ['address_1', 'address_2', 'city', 'state', 'zipcode', 'country'];
    return array_reduce(array_keys($map), function ($output, $key) use ($map, $entry, $field) {
        return str_replace("[$map[$key]]", $entry[$field->id . '.' . ++$key], $output);
    }, $format);
}, 10, 3);

The new output will be:

Address 1
City, State Zipcode