jQuery & the WordPress Rest API – 1st Image as Background

Ordinarily it’s pretty easy to get the featured image from the WordPress API. You just have to remember to add the _embed element like so https://bionicteaching.com/wp-json/wp/v2/posts?_embed

But maybe there’s some reason you don’t want to set the featured image but want to get the first image from the body of the post. This chunk of so very uncool jQuery gets the JSON data and finds the first img src URL in the post body.

I’ve gone over the basic pieces previously so here’s the portion that differs. It’s just regex searching for anything with the img src pattern and spitting back out the URL.

function findBgImg(content){
  img = content.match('<img [^>]*src="([^"]*)"[^>]*>');  
  if (img && img[1]){
    return img[1]; 
  } else {
    return 'https://c1.staticflickr.com/5/4655/26616606138_0942be75c9.jpg'//whatever your default image might be if it can't find one
  }
}

See the Pen antonio – jquery demo by Tom (@twwoodward) on CodePen.

Comments on this post

No comments.

Leave a Reply

Trackbacks and Pingbacks on this post

No trackbacks.

TrackBack URL