【问题标题】:How to echo the ACF Google Maps address如何回显 ACF 谷歌地图地址
【发布时间】:2021-12-30 23:11:07
【问题描述】:

这里是 PHP 新手...我正在尝试显示 ACF Google 地图字段的地址。

我认为以下代码会将地址显示为:123 Main Street, Charlotte, NC 28216, USA 但没有返回任何内容。

<?php 
$map_location = get_field('location');
echo $map_location['location'];
?>

我能够让它工作,但它在门牌号后面加一个逗号,在邮政编码后面加一个句点,这看起来有点奇怪。前任。 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>';
}
?>

有谁知道如何将 ACF 谷歌地图地址回显为 123 Main Street, Charlotte, North Carolina, 28216?

【问题讨论】:

    标签: php google-maps advanced-custom-fields


    【解决方案1】:

    您可以为“,”分隔符使用一个变量,当您的位置数组键为“街道编号”时,该变量将变为空格

    print_r($location) 应该输出如下内容:

    Array
    (
        [street_number] => 123
        [street_name] => Example Street
        [city] => Melbourne
        [state] => Victoria
        [post_code] => 3000
        [country] => Australia
    )
    

    返回的字段数据是一个关联数组。
    因此,您也可以通过其键输出每个元素,如下所示:

    echo $location['street_number'];
    

    修改后的输出是这样的:

    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>';
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-28
      • 2018-09-27
      • 2013-08-08
      相关资源
      最近更新 更多