2

I'm using wp cli to import the same featured image for around 2,000 posts. I did a couple tests to see if the image would be duplicated or if WordPress would notice that the image already exists in the media library and use it. Sadly it just duplicates the image.

Command I'm using: wp media import http://example.com/wp-content/uploads/sites/30/2016/04/picture_name.jpg --post_id=x --title="Pluto Mosaic" --featured_image --url=mysite.example.com

Is there another way to do this without having to import the same image 2,000 times?

Thanks, j03

2

You can use wp media import to import the image once. Once you have the ID for the attachment created, you can run:

wp post list --post_type=post --format=ids | xargs -0 -d ' ' -I % wp post meta add % _thumbnail_id <thumbnail-id>

Make sure to replace <thumbnail-id> with the actual attachment ID.

0

You should be able to write a php script to do this for each post. You'll need to do a query to get all the posts, then loop through that setting the featured image to your desired image on each post.

This question has specific code that should get you started.

0

This Worked for me very well.

# 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:

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 to xargs 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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