Skip to content

Instantly share code, notes, and snippets.

@HoverBaum
Created March 26, 2018 08:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HoverBaum/a4ecf88072d7936beb660eac135d3c21 to your computer and use it in GitHub Desktop.
Save HoverBaum/a4ecf88072d7936beb660eac135d3c21 to your computer and use it in GitHub Desktop.
const generateAssetsList = (posts, baseUrl, simpleLog = console.log) => new Promise(async resolve =>{
const apiURL = `${baseUrl.replace(/\/$/, '')}/wp-json/wp/v2/media`
simpleLog('Reducing posts to asset numbers')
let infosFetched = 0
// First add the featured_media images and get ther URLs.
const featuredAssets = await Promise.all(posts.reduce((all, post) => {
if (!post.featured_media) return all
return all.concat([{
mediaNumber: post.featured_media,
postId: post.id
}])
}, [])
.map(async ({mediaNumber, postId}, i , array) => {
const featuredMedia = await getJSON(`${apiURL}/${mediaNumber}`)
infosFetched += 1
simpleLog(`Getting info about assets ${infosFetched}/${array.length}`)
return {
mediaNumber,
link: featuredMedia.guid.rendered,
title: featuredMedia.title.rendered || `asset${i}`,
description: featuredMedia.alt_text || '',
postId
}
// After all this we also add images from the body of posts.
}))
const assets = featuredAssets.concat(posts.reduce((all, post) => {
const images = post.bodyImages ? post.bodyImages : []
return all.concat(images)
}, []))
resolve(assets)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment