WordPress is a fantastic CMS. Although very functionally rich, it also provides extensibility options via its plugin system. Sometimes it may not be enough though, one of the reasons for this may be that the functionality you’re looking for is too specific, so there’s no big incentive for someone to write a general purpose plugin for this.
Like my case, for example: duplicate featured image for every published post. There is no such functionality (“copy image”) in WordPress Media Library and I failed to find a WP plugin for this. Therefore I had to automate.
One of the ways how to do this is using XML RPC API provided by WordPress itself. I decided to use WP CLI though because it is a fantastic command line tool that works with Bash shell scripting. It is also a very useful admin tool, for example, for upgrading your WP plugins or the WP core install.
Copying Featured Images
So here’s the script:
What it does here, it uses the WP CLI tool to list all published posts in one list (
--nopaging=1), then it finds the featured image entry (which is also a “post” from WP perspective). Notice that we use the fantastic jq tool here to parse JSON returned by the
wp command. The reason for this is, well, I could not figure out how to retrieve a single row containing the value of
_thumbnail_id meta key.
Provided we have the actual thumbnail id (
$mediaID) we find the actual URL of the image (
guid field of the post object), download it locally and then just impor it back and attach to the very same post.
You (or someone else using particular WP installation) can the find all the duplicated images in Media library by searching for “Duplicate featured image” or “post id <your id here>”.
Of course, this script lacks some error detection, it also assumes that all images are in JPEG format etc etc., however I hope someone may find this useful.