1

This question has probably been asked somewhere else, but I guess I haven't been able to put the right search terms together to get the answer I'm looking for to pop up in the Google abyss.

I am trying to retrieve data from an external API and update an existing custom post with the data.

I have already created the custom post type with ACF and created a post. Now I want to update the fields in the custom post with data from the API.

BONUS: Additionally, this API is nested at various levels, so let's say I wanted to update field data with a value nested a couple of layers deep, how would I get to that value?

I've tried ACF's update_field and I've tried Wordpress's native wp_update_post and update_post_meta, but cannot seem to get either to work.

Here's what I have so far:

$url = "https://api.weather.gov/points/39.7456,-97.0892";
    $res = wp_remote_get($url);
    $res_body = wp_remote_retrieve_body($res);
    $json_data = json_decode($res_body, true);

    $post_id = 21;  
    update_post_meta($post_id, "field_6636a2a494dbe", $json_data["properties"]["forecast"]);

Any advice would be greatly appreciated! Thanks!

1
  • how you use json data looks like good. what doesn't work as expected ? Commented Apr 9 at 7:57

2 Answers 2

0

Use the ACF field name, not the field key. This works:

update_field('forecast_link', $json_data['properties']['forecast'], $post_id);

update_post_meta($post_id, 'forecast_link', $json_data['properties']['forecast']);

Use array keys to access nested data as needed.

Reference (ACF Docs): https://www.advancedcustomfields.com/resources/update_field/

1

I figured it out! For some reason, it did not like the actual ACF field key in the update_post_meta arguments, but once I switched it to the field name it worked like a charm!

update_post_meta($post_id, "forecast_link", $json_data["properties"]["forecast"]);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.