【问题标题】:Get Json Data when a variable matches with ACF custom field in WooCommerce当变量与 WooCommerce 中的 ACF 自定义字段匹配时获取 Json 数据
【发布时间】:2017-10-16 20:29:36
【问题描述】:

我正在尝试从要加载到我的 WooCommerce 网站的 json 文件中获取数据。我想从我抓取的网站产品的匹配名称中获取价格。

我需要产品的名称来匹配我添加到产品页面的值高级自定义字段,我添加到 Wordpress 的产品页面中,然后如果名称与我添加的属性匹配则获取价格。

下面的代码部分工作,但由于某种原因,高级自定义字段值的调用不起作用。它显示文本的值,而不是将其与 json 中的 name 字段匹配有什么建议吗?

$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;

【问题讨论】:

  • 这里有什么问题.... the_field('apmex_vendor_name') 不起作用吗?因为 foreach 在我的测试中运行良好
  • 所以结果是“apmex_vendor_name”的值打印在“不可用”旁边,而不是返回与“apmex_vendor_name”字段匹配的对象名称的结果。我说得通吗?

标签: php json wordpress woocommerce advanced-custom-fields


【解决方案1】:

在您的代码中使用$vendorName = the_field('apmex_vendor_name'); 将不起作用,因为ACF 函数the_field() 等效于echo get_field();,如果您想在变量中设置值,则无法工作......

你应该简单地使用get_field():

$vendorName = get_field('apmex_vendor_name');

现在应该可以了……

你的其余代码似乎是正确的(我已经测试过了)......

【讨论】:

  • 哦,天哪,我不敢相信我错过了。太感谢了。它工作得很好。谢谢谢谢!
  • 再次感谢,我正在修改一点以匹配结构略有不同的 json 文件。当像这样识别json时有层次结构吗?或者php可以用来识别对象的“名称”吗?
  • 好的,所以我遇到的最后一个问题是这里的这个 json 文件,它的结构与我的问题中的第一个文件略有不同:gold.explorethatstore.com/wp-content/themes/… 我想我的原始 php 不能处理这个文件,那么我的 $value 会改变吗?我只是对为什么它不会是相同的功能感到困惑。
  • 我如何确保您得到问题?
  • 好的,我在这里问过:stackoverflow.com/questions/46780953/…
猜你喜欢
  • 2018-03-28
  • 1970-01-01
  • 1970-01-01
  • 2019-01-13
  • 2021-04-12
  • 1970-01-01
  • 2019-04-17
  • 2022-11-07
  • 1970-01-01
相关资源
最近更新 更多