Populating ACF Image Fields from JSON file

admin2025-01-08  3

I am wondering if any ACF pros can help me here. I am considering auto populating custom posts that have ACF fields from an external JSON file created by an APP. this would update every 30minutes by Cron Job. What i am wondering is because each post will have anywhere between 3 to 15 images, how best to go about this? Is it possible to add images to an ACF gallery field from the image urls in the JSON file? Or do i need to set up a Repeater with oEmbed fields for the image URLs to go into? Or is there another option?

I am wondering if any ACF pros can help me here. I am considering auto populating custom posts that have ACF fields from an external JSON file created by an APP. this would update every 30minutes by Cron Job. What i am wondering is because each post will have anywhere between 3 to 15 images, how best to go about this? Is it possible to add images to an ACF gallery field from the image urls in the JSON file? Or do i need to set up a Repeater with oEmbed fields for the image URLs to go into? Or is there another option?

Share Improve this question asked Apr 22, 2021 at 5:41 bjamesbjames 1 3
  • Sorry, but third party plugins (ACF) are off topic here. Even if they were on topic, your question would still be "primarily opinion based" - meaning there is likely no definite answer to it other than opinions. Have you tried both approaches? Which one works better for you? – kero Commented Apr 22, 2021 at 6:49
  • I'm sorry, there seems to be a lot of topics about ACF on here. Are you a staff/moderator? I'm not looking for plugin support as such, just advice from others about my topic, maybe someone can point me in the right direction? – bjames Commented Apr 22, 2021 at 11:03
  • I'm not, moderators will have a diamond shape next to their name. But you can read more in the help on "What topics can I ask about here?". – kero Commented Apr 22, 2021 at 12:42
Add a comment  | 

1 Answer 1

Reset to default 0

Yes it is possible to populates an acf gallery field from json data.

Lets say this is your gallery json from your app...

{
    "gallery" : [
        "https://i.imgur.com/VHkyr8P.jpeg",
        "https://i.imgur.com/obdqDwa.jpeg",
        "https://i.imgur.com/eQuSNVx.jpeg",
        "https://i.imgur.com/1lVyIJt.jpeg",
        "https://i.imgur.com/5uIOviX.jpeg"
    ]
}

Now in your cron job you could run a function as shown below to handle acf gallery field image updates.

My example function below gets any existing acf gallery images, retains them and merges new images to the gallery field...

/**
 * @param $post_id int
 * @param $acf_gallery_field_name string
 * @param $json_url string
 */
function add_json_imgs_to_acf_gallery($post_id, $acf_gallery_field_name, $json_url) {

    // get the json data via url
    $json = file_get_contents($json_url);

    // decode json to array
    $array = json_decode($json,true);

    // if decoded json is array and has array key gallery (as per above json example)
    if (is_array($array) && array_key_exists('gallery')) {

        // lets begin multiple attachment array
        $attach_ids = [];

        // foreach of your json gallery urls
        foreach ($array['gallery'] as $img_url) {

            // check the type of file
            // we'll use this as the 'post_mime_type'
            $file_type = wp_check_filetype(basename($img_url),null);

            // get the path to the upload directory
            $wp_upload_dir = wp_upload_dir();

            // prepare an array of attachment post data
            $attachment = [
                'guid' => $wp_upload_dir['url'] . '/' . basename($img_url),
                'post_mime_type' => $file_type['type'],
                'post_title' => preg_replace('/\.[^.]+$/', '',basename($img_url)),
                'post_content' => '',
                'post_status' => 'inherit'
            ];

            // insert the attachment
            $attach_id = wp_insert_attachment($attachment,$img_url,$post_id);

            // make sure that this file is included, as wp_generate_attachment_metadata() depends on it
            require_once(ABSPATH . 'wp-admin/includes/image.php');

            // generate the metadata for the attachment, and update the database record
            $attach_data = wp_generate_attachment_metadata($attach_id,$img_url);
            wp_update_attachment_metadata($attach_id,$attach_data);

            // build attachment id's as an array
            $attach_ids[] = $attach_id;

        }

        // get our current acf gallery field images
        $gallery = get_field($acf_gallery_field_name,$post_id);

        // if we already have galley images
        if($gallery) {

            // empty array for existing gallery image id to be populated
            $existing_attach_ids = [];

            // for each gallery item as array key => image array
            foreach ($gallery as $key => $img) {

                // add image id to existing attachment ids 
                $existing_attach_ids[] = $img['ID'];

            }

            // merge existing acf gallery ids with newly json uploaded image items
            $attach_ids = array_merge($existing_attach_ids,$attach_ids);

            // update acf gallery field with merged attachment ids
            update_field($acf_gallery_field_name,$attach_ids,$post_id);

        } else {

            // update acf gallery field with new attachment ids
            update_field($acf_gallery_field_name,$attach_ids,$post_id);

        }

    }

}
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736268377a1270.html

最新回复(0)