I am attaching an image to a post with the media import command.

I know I can get the image id using the --porcelain option, but how can I get the image url from this id?

Or is there a way to display the featured image's url of a post (apparently the list command does allow this)?

4 Answers 4


Assuming the attachment ID were in a variable of $attachment_id you could use the following command:

# get attachment URL
wp db query "SELECT guid FROM $(wp db tables *_posts) WHERE ID=\"$attachment_id\"" | head -n 2 | tail -1

I use the $(wp db tables *_posts) bit just in case the wp_ table prefix is non-default.


WP-CLI as of v1.4.0 can extract and store serialized data with the "pluck" and "patch" commands.

In the above case, a problem I needed to solve, I use the expression below to obtain the source image filename from a post ID (the post the image is attached to):

wp post meta pluck $(wp post meta get <post_ID> _thumbnail_id) _wp_attachment_metadata file

Note that this code will pull the relative post media path, e.g.: 2018/09/. The dirname portion can easily be stripped with e.g.:

basename "$(wp post meta pluck $(wp post meta get <post_ID> _thumbnail_id) _wp_attachment_metadata file)"
  • but what if the image is not attached to any post? Can I get the url of the image just from its attachment id?
    – Sulli
    Commented Nov 14, 2018 at 21:40
  • @Sulli Yes, you could list media attachments (attached or not) with: wp post list --post_type=attachment then pull URL with wp post get [ID] --field=guid as mentioned by another commenter last year
    – GainRider
    Commented Nov 16, 2018 at 16:12

Media attachments are tricky to get through the cli because they are stored as a serialised array in the DB and then generated using PHP functions, I don't think you can get this using the default wp-cli commands.

However you can install the RESTful wp-cli package as well as the WordPress REST API plugin to get the image URL easily, just do:

# Install dependencies
wp package install wp-cli/restful && wp plugin install rest-api --activate

# Print URL
wp rest attachment get $image_id --field=source_url

If you want to get original uploaded file url, you can do it this way:

wp post get <ID> --field='guid'

This will return guid column (which is absolute url) from wp_posts table for given ID.

If you want to get some file generated from your original file, you have to alter filename at the end of the url to reflect some of the generated sizes. You can get filenames for all sizes from serialized array stored in wp_postmeta for this image. Meta key is _wp_attachment_metadata. Try following command to get this with wp cli

 wp post meta get <ID> _wp_attachment_metadata

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.