Use WP-CLI to bulk import images to the WordPress media library.
wp media import command creates attachments from local files or URLs. The utility has the ability to recurse through subdirectories, making it very useful.
A typical workflow might involve:
- Getting the raw images
- Bulk renaming image files (e.g. to include client details and an index number)
- Bulk image processing using a custom script
wp media importto import images, either to a local dev site or a staging site
WP-CLI makes it easy to run a bulk import from the command line:
The command works recursively, but relies on the glob capabilities of the current shell.
“Globbing” is what the shell does when it encounters a wildcard (like “*”) in a command. Bash 4.0 offers an option called
globstar which is used for “**”. As seen in the command above, the “**” pattern allows the command to recurse all directories.
Under Ubuntu 16.04, the globstar option must be turned on for this to work. By default, it isn’t - and the command will not act recursively. To turn globstar on:
Attach an Image to a Post
wp media import command can also be used to import images as featured images for specified posts:
Import an Image as the Featured Image for All posts
This is a pretty handy feature for setting up development sites:
--porcelainoption causes the new attachment ID to be output, so this line runs the import and sets the $ATT_ID shell variable to the imported image ID
wp post list --post_type=post --format=idsgets a list of post IDs in a space-separated string format and passes this to
xargsoperates on each ID, setting the post meta
_thumbnail_idfield for each post ID. The
xargsoptions set a space as the delimiter
comments powered by Disqus