简体   繁体   中英

Get Json Data when a variable matches with ACF custom field in WooCommerce

I am trying to get data from a json file to be loaded into my WooCommerce website. I would like to get the price from the matching name of the product of the site that I crawled.

I need the name of the product to match the value advanced custom field that I added to the product pages I added into the product page on Wordpress then to get the price if the name matches the attribute I added.

The code below partially worked, but for some reason the call for the advanced custom field value is not working. It displays the value of the text instead of matching it to the name field in json Any advice?

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

Using $vendorName = the_field('apmex_vendor_name'); in your code will not work, because ACF function the_field() is equivalent of echo get_field(); which cant work if you want to set the value in a variable…

Instead you should simply use get_field() :

$vendorName = get_field('apmex_vendor_name');

Now it should work…

The rest of your code seems correct (I have test it)…

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM