Transfer images from Airtable to WordPress media library using JavaScript APIs

I need help building a JavaScript script that fetches images from my Airtable database and uploads them to WordPress media library. The goal is to automatically populate empty image fields across different post types in WordPress.

For instance, if I have a user profile for “John Smith” with an empty avatar field, the script should grab the corresponding image from Airtable and set it as the profile picture in WordPress.

I’m a beginner programmer learning as I go, so any guidance on the approach would be appreciated. Here’s what I have so far for connecting to Airtable:

const airtableClient = new Airtable({ apiKey: 'YOUR_API_KEY' }).base('YOUR_BASE_ID');

const profileTable = airtableClient('PROFILES');

const fetchAllProfiles = async() => {
    const profileData = await profileTable.select({
        maxRecords: 100,
        view: "Main View"
    }).firstPage();
    console.log(profileData);
};

fetchAllProfiles();

const fetchSingleProfile = async(recordId) => {
    try {
        const profile = await profileTable.find(recordId);
        console.log(profile);
    } catch (error) {
        console.error(error);
    }
};

fetchSingleProfile();

How do I extend this to download the images and push them to WordPress?

Been down this road before with a similar project at my company. You need to handle the image transfer in steps.

First, grab the attachment URL from your Airtable record:

const imageUrl = profile.fields['Profile Image'][0].url;

Then fetch the image data and convert it to a File object:

const response = await fetch(imageUrl);
const blob = await response.blob();
const fileName = imageUrl.split('/').pop();
const file = new File([blob], fileName, { type: blob.type });

For the WordPress upload, create a FormData object and POST it:

const formData = new FormData();
formData.append('file', file);

const wpResponse = await fetch('https://yoursite.com/wp-json/wp/v2/media', {
    method: 'POST',
    headers: {
        'Authorization': 'Bearer YOUR_WP_TOKEN'
    },
    body: formData
});

const mediaData = await wpResponse.json();

WordPress authentication is the tricky part. I’d use the Application Passwords plugin for easier token management.

Once uploaded, you get back a media ID that you can attach to posts or user profiles through more API calls.

u’ll need to use the WordPress REST API along with your Airtable script. First, get the image URL from Airtable, download it as a blob, then upload it to /wp-json/wp/v2/media with the appropriate auth headers. Make sure to use multipart/form-data and include your WordPress auth token!