Bulk Import Images Using WP-CLI
WP-CLI, WordPress
Use WP-CLI to bulk import images to the WordPress media library.
The 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
- Use
wp media import
to import images, either to a local dev site or a staging site
Bulk Import
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
The WP-CLI 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:
Walkthrough:
- The
--porcelain
option 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=ids
gets a list of post IDs in a space-separated string format and passes this toxargs
xargs
operates on each ID, setting the post meta_thumbnail_id
field for each post ID. Thexargs
options set a space as the delimiter
Resources
comments powered by Disqus