Reputation: 1
PHP noob here... I'm trying to display the address of an ACF Google Maps Field.
I would think that the following code would display the address as: 123 Main Street, Charlotte, NC 28216, USA but nothing is returned.
<?php
$map_location = get_field('location');
echo $map_location['location'];
?>
I was able to get this to work, but it ads a comma after the house number, and a period after the zip code, which looks kind of strange. ex. 123, Main Street, Charlotte, North Carolina, 28216.
<?php
$map_location = get_field('location');
if( $map_location ) {
// Loop over segments and construct HTML.
$address = '';
foreach( array('street_number', 'street_name', 'city', 'state', 'post_code') as $i => $k ) {
if( isset( $map_location[ $k ] ) ) {
$address .= sprintf( '<span class="segment-%s">%s</span>, ', $k, $map_location[ $k ] );
}
}
// Trim trailing comma.
$address = trim( $address, ', ' );
// Display HTML.
echo '<p>' . $address . '.</p>';
}
?>
Does anyone know how to echo the ACF Google Maps address as 123 Main Street, Charlotte, North Carolina, 28216?
Upvotes: 0
Views: 1581
Reputation: 17307
You can use a variable for the ',' delimiter that will change to a space when your location array key is 'streetnumber'
print_r($location)
should output something like this:
Array
(
[street_number] => 123
[street_name] => Example Street
[city] => Melbourne
[state] => Victoria
[post_code] => 3000
[country] => Australia
)
The returned field data is an associative array.
Thus you might also output each element by its key like so:
echo $location['street_number'];
The modified output would be something like this:
if( $location ) {
// Loop over segments and construct HTML.
$address = '';
$location_fields = array('street_number', 'street_name', 'city', 'state', 'post_code', 'country');
foreach( $location_fields as $i => $k ) {
$delimiter = ', ';
if( isset( $location[ $k ] ) ) {
// reset delimiter
if($k=='street_number'){
$delimiter = ' ';
}
$address .= sprintf( '<span class="segment-%s">%s</span>'.$delimiter, $k, $location[ $k ] );
}
}
// Trim trailing comma.
$address = trim( $address, ', ' );
// Display HTML.
echo '<p>' . $address . '.</p>';
}
Upvotes: 1