所以我使用以下代码段来构建 URL 结构:
$map_url = 'https://google.com/maps/search/'.get_field('brand', $office).
' '.get_field('location', $office).
' '.get_field('address_line_1', $office).
', '.get_field('address_line_2', $office).
', '.get_field('city', $office).
', '.get_field('state', $office).
', '.get_field('zip_code', $office).
', '.get_field('country', $office);
当缺少字段时,我得到以下输出:
<块引用>Edificio World Trade Center, Torre B, Avenida Francisco de Orellana, 瓜亚基尔, , , 厄瓜多尔
如果字段为空,是否可以避免附加逗号?或者有没有更好的方法来使用所有 ACF 字段来构建我的 URL?
答案 0 :(得分:1)
我会使用带有 implode()
的数组,因此我们不需要手动检查每个值。
我们可以使用 array_filter()
删除任何“无效”(空)值。
看看这个例子
<?php
// Empty array
$res = [];
// Push some values
$res[] = 'location';
$res[] = 'Guayaquil';
$res[] = ''; // Empty string to 'fake' invalid get_field result
// Remove any empty values
$res = array_filter($res);
// Implode the array with ', '
$res = implode(', ', $res);
// Show result
echo $res;
// location, Guayaquil