Categories
CMS Mastering Development Wordpress

Uploading a media item with the wp-json API to a specific path

I’m using the WP-JSON API to import all my posts from my live site to my development site. It’s working fine for posts, categories and authors, but when I upload my images, the API treats the files as having been uploaded that day (so for example, as we’re in June 2020, the files all go to wp-content/uploads/2020/06), which results in broken image links. How can I upload files as if they’re uploaded on the same date as the source file?

Here’s what I have so far (where $MEDIA is a response from my production server to /wp-json/wp/v2/media to list all my media files):

# Loop through the JSON response (encoding as base64, so each object is on a seperate line)
for media in $(printf %s "$MEDIA" | jq -r ".[] | @base64")
do
  media_body=$(printf %s "$media" | base64 -D)
  # Get URL and destination path
  source_url=$(printf %s "$media_body" | jq .source_url | tr -d '"')
  destination_path=$(printf %s "$media_body" | jq .media_details.file | tr -d '"')

  filename=$(basename "$destination_path")

  # Download media file to tmp directory
  curl -s "$source_url" > "/tmp/$filename"

  # Upload the media file to my dev server (store the response as a variable so we can get the ID)
  response=$(curl --request POST "http://localhost/wp-json/wp/v2/media/" \
    -u admin:admin \
    -s \
    --header "cache-control: no-cache" \
    --header "content-disposition: attachment; filename=$filename" \
    --data-binary "@/tmp/$filename" \
    --location)

  id=$(printf %s "$response" | jq -r ". | .id")
  body=$(printf %s "$media_body" | jq -r ". | {date: .date, date_gmt: .date_gmt, slug: .slug, status: \"publish\", title: .title.rendered}")

  # This outputs body eg {"date": "2020-05-27T12:12:53", "date_gmt": "2020-05-27T12:12:53", "slug": "cropped-shortcut-icon-png", "status": "publish", "title": "cropped-shortcut-icon.png" }

  # Update the image's metadata
  curl --location --request POST "http://localhost/wp-json/wp/v2/media/$id" \
    -u admin:admin \
    -s -o /dev/null \
    --header 'Content-Type: application/json' \
    --data-raw "$body"
done

Leave a Reply

Your email address will not be published. Required fields are marked *