Dev Notes

Software Development Resources by David Egan.

Bulk Import Images Using WP-CLI


WP-CLI, WordPress
David Egan

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:

# Import all images from a local directory, without attaching to posts
wp media import ~/Pictures/processed-images-medium/\*\*\/\*.jpg

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:

shopt -s globstar
wp media import ~/Pictures/processed-images-medium/\*\*\/\*.jpg

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:

wp media import ~/Pictures/image.png --post_id=123 \
--title="A downloaded picture" --featured_image
# See: http://wp-cli.org/commands/media/import/#examples

This is a pretty handy feature for setting up development sites:

# Line 1
ATT_ID="$(wp media import ~/Pictures/swimming.jpg --porcelain)"
# Line 2
wp post list --post_type=post --format=ids | \
# Line 3
xargs -0 -d ' ' -I % wp post meta add % \_thumbnail_id $ATT_ID

Walkthrough:

  1. 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
  2. wp post list --post_type=post --format=ids gets a list of post IDs in a space-separated string format and passes this to xargs
  3. xargs operates on each ID, setting the post meta _thumbnail_id field for each post ID. The xargs options set a space as the delimiter

Resources


comments powered by Disqus