Set WordPress Featured Image Using Javascript

Setting featured images for a post in WordPress can be rather time-consuming, especially, when you do not care too much what the images. For example, if you are writing about a movie, the movie poster will probably make a perfect featured image. You just have to go looking through the gallery to find it. This gave me the idea to build a small meta box that would attempt to suggest a featured image to use for the post automatically. One-click and the featured image is set, saving you 30 seconds of valuable time that can be better spent producing awesome content for your blog.

Setting a featured image for a post in the back end is a fairly easy task to perform and is well documented. Setting it via JavaScript is not something you see so often, as most people don’t see the need for it when the WordPress editor already has a way to set a featured image. After doing some digging, I eventually got to the bottom of it and was able to create the tool I needed that would make life super simple setting featured images in WordPress using Javascript.

wp.media.featuredImage.set(attachmentId);

Yep, that’s it! The code above was all I needed to set a featured image inside the WordPress post editor page. I wrote a javascript function that would make an Ajax call to a PHP script. The call would pass information about the post I was writing. The PHP script would then scan the wordpress post database to find similarly tagged posts. It would then fetch the featured image of those posts and if it existed, it would return it. The tool then displayed the list of images. When the image was clicked, I would call the line of code above and BAM. The UI automatically updated to set that featured image for me without any additional code. Very simple idea and a handy solution for those like me who just want some nice art to put at the top of blog posts.