WP-CLI: wp wc product update images

I’m running WordPress inside a Docker container, and wanted to control the website with command lines, and code. The two options are to use the REST API, or to use the WP-CLI interface.

I opted for the CLI because I assumed it was faster. I suspect I’m wrong, but I’m sticking with it for now, because it’s generally easy to use. (I will eventually move to the REST API. See below.)

You create your command lines in the terminal, and then copy them into your code, and execute them with shell_exec().

I create a file uploader based on this command:

wp media import /path/to/file

It works. It’s also pretty slow, but tolerable. (On my system, and upload takes 10 seconds.)

I wanted to add some metadata to the upload, so I could search for it later.

This created a chicken-and-egg problem because you need an post ID to upload and set metadata.

So I wrote a function to create a product for the SKU, if one didn’t already exist.

The good news – the attachments seem to go up correctly, with metadata. The bad news – these attachments don’t show up on Woocommerce products.

The product must be updated to use these images after the files are uploaded.

It gets tricky because you need to pass an array of objects to the CLI, but I couldn’t find any documentation about the format for the –images option.

Here’s an example of a command line that worked.

wp wc product update 8729 '--images=[{"id":8730},{"id":8731}]' --user=johnk

The value is an array of objects, where each object can be an ID of an uploaded image. The syntax is JSON.

The command will automatically expand the objects into more elaborate objects with metadata.

Why Move from the CLI to the REST API?

I was getting error statuses and messages, and found I couldn’t get at the error message text.

The more I use the CLI as an API, the more I need to parse the output, so for every line of CLI code, there’s a line or two of decoding JSON and interpreting that.

That, combined with the complexity of creating the above string, is pushing me away from the CLI, for what I’m doing. I’ll continue to use the CLI as a prototyping tool, and for regular administration.

Was this helpful?

0 / 0

Leave a Reply