我试图在google api url中使用自定义字段值。
我有2个自定义字段。我需要在url中输出这些自定义字段的值。
自定义字段键:
app_collection-postcode
app_delivery-postcode
这是谷歌的url。我需要把这两个邮政编码替换为
$postcode1
&;
$postcode2
$url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=$postcode1&destinations=$postcode2&mode=driving&language=en-EN&sensor=false";
我试过以下几种方法,哪种有效。我下面的问题是我出于某种原因
3333
显示在
echo
它使用数组作为单值键。
$custom_fields = get_post_custom(the_ID());
$my_custom_field = $custom_fields[\'app_collection-postcode\'];
$custom_fields2 = get_post_custom(the_ID());
$my_custom_field2 = $custom_fields2[\'app_delivery-postcode\'];
$url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=$my_custom_field[0]&destinations=$my_custom_field2[0]&mode=driving&language=en-EN&sensor=false";
$data = @file_get_contents($url);
$result = json_decode($data, true);
foreach($result[\'rows\'] as $distance) {
echo \'Distance from you: \' . $distance[\'elements\'][0][\'distance\'][\'text\'] . \' (\' . $distance[\'elements\'][0][\'duration\'][\'text\'] . \' in current traffic)\';
}
以上输出:
3333Distance from you: 1.9 km (4 mins in current traffic)
有没有办法简化上述内容,因为它看起来很笨重,而且我也不确定为什么我会得到
3333
最合适的回答,由SO网友:Sumit 整理而成
您正在使用the_ID()
而不是get_the_ID()
. 这就是echo
.
还有为什么要使用这么多变量并提取所有元键。我建议使用以下代码get_post_meta()
.
$my_custom_field = get_post_meta(get_the_ID(), \'app_collection-postcode\', true);
$my_custom_field2 = get_post_meta(get_the_ID(), \'app_delivery-postcode\', true);
$url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=$my_custom_field&destinations=$my_custom_field2&mode=driving&language=en-EN&sensor=false";
$data = @file_get_contents($url);
$result = json_decode($data, true);
foreach($result[\'rows\'] as $distance) {
echo \'Distance from you: \' . $distance[\'elements\'][0][\'distance\'][\'text\'] . \' (\' . $distance[\'elements\'][0][\'duration\'][\'text\'] . \' in current traffic)\';
}