当变量与 WooCommerce 中的 ACF 自定义字段匹配时获取 Json 数据
Get Json Data when a variable matches with ACF custom field in WooCommerce
我正在尝试从 json 文件中获取数据以加载到我的 WooCommerce 网站中。我想从我爬取的站点产品的匹配名称中获取价格。
我需要产品的名称来匹配我添加到产品页面的值高级自定义字段我添加到 Wordpress 的产品页面然后如果名称与我添加的属性匹配则获取价格。
下面的代码部分起作用,但由于某种原因,对高级自定义字段值的调用不起作用。它显示文本的值,而不是将其与 json 中的名称字段匹配。有什么建议吗?
$str = file_get_contents('http://gold.explorethatstore.com/wp-content/themes/divi-ETS-child-theme/run_results_apmex.json');
// decode JSON
$json = json_decode($str, true);
// default value
$coinPrice = "Not Available";
$vendorName = the_field('apmex_vendor_name');
// loop the json array
foreach ($json['coin'] as $value){
// check the condition
if ($value['name'] == $vendorName){
$coinPrice = $value['price']; // get the price
break; // exit the loop
}
}
echo $coinPrice;
在您的代码中使用 $vendorName = the_field('apmex_vendor_name');
将不起作用,因为 ACF 函数 the_field() 等效于 echo get_field();
如果您想在变量中设置值,则无法工作...
相反,您应该简单地使用 get_field()
:
$vendorName = get_field('apmex_vendor_name');
现在应该可以了……
你的其余代码似乎是正确的(我已经测试过了)…
我正在尝试从 json 文件中获取数据以加载到我的 WooCommerce 网站中。我想从我爬取的站点产品的匹配名称中获取价格。
我需要产品的名称来匹配我添加到产品页面的值高级自定义字段我添加到 Wordpress 的产品页面然后如果名称与我添加的属性匹配则获取价格。
下面的代码部分起作用,但由于某种原因,对高级自定义字段值的调用不起作用。它显示文本的值,而不是将其与 json 中的名称字段匹配。有什么建议吗?
$str = file_get_contents('http://gold.explorethatstore.com/wp-content/themes/divi-ETS-child-theme/run_results_apmex.json');
// decode JSON
$json = json_decode($str, true);
// default value
$coinPrice = "Not Available";
$vendorName = the_field('apmex_vendor_name');
// loop the json array
foreach ($json['coin'] as $value){
// check the condition
if ($value['name'] == $vendorName){
$coinPrice = $value['price']; // get the price
break; // exit the loop
}
}
echo $coinPrice;
在您的代码中使用 $vendorName = the_field('apmex_vendor_name');
将不起作用,因为 ACF 函数 the_field() 等效于 echo get_field();
如果您想在变量中设置值,则无法工作...
相反,您应该简单地使用 get_field()
:
$vendorName = get_field('apmex_vendor_name');
现在应该可以了……
你的其余代码似乎是正确的(我已经测试过了)…