Automated Uploading of Image Media to WordPress

In terms of documenting the build progress I’ve settled on a basic pattern of uploading an “end of day” photo from the time-lapse camera and then adding that to a daily Post, both with a title of “Week A, Day B“. I’ve been doing that manually up to now but since there’s a pattern it means it’s something that can be automated with a little code.

From the research I’ve done so far it seems the standard way of doing such things is to use WP-CLI, a Command Line Interface for WordPress which must be run on the same computer as is hosting the WordPress installation. The CLI supports various operations relating to the installation and maintenance of WordPress itself and also the management of content like Posts and Media.

As a first step I’ve automated the uploading of the 16:00 daily photo as a WordPress Media item which can then be manually embedded in a Post. (All the hourly snapshot photos have always been automatically copied to the same server as is hosting WordPress anyway.) As a test I’ve also managed to automatically create a Post but automatically inserting the Media into the Post is proving more challenging so I’ll come back to look at that later.

Update 2015-11-17: Turns out inserting Media into a Post isn’t all that complicated after all. I’ve settled on the following approach:

  • Create a placeholder for the Post, recording the Post ID number once that is created.
  • Upload the Media (image file), specifying that it should be Attached to the Post by citing the Post ID number and recording the Media ID number which is returned as a result of a successful upload.
  • Going back to Update the Post, generating a file containing the Post content, which is the visible text plus quite a bit of HTML for the attachment of the image. That HTML requires knowledge of the Media ID number, which is why it can’t be specified before the Media has been uploaded.

Seems to work OK. When I get chance I come back and add some more descriptive text manually but at least the daily photos should be visible without any human intervention.

I’m not sure if the 16:00 photo will be usable once we get closer to the shortest day. It might be too dark, in which case I’ll need to use the 15:00 photo instead.

CC BY-SA 4.0 Automated Uploading of Image Media to WordPress by Marsh Flatts Farm Self Build Diary is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.