Complementing WP-CLI
WP-CLI is a command-line tool to interact with WordPress, that helps us automate tasks. It allows us to install a new site, create or update posts, activate plugins, modify the options, and much more.
WP-CLI commands can be nested:
- Execute a WP-CLI command that returns the ID of some resource
- Inject that ID into another WP-CLI command, to execute an operation on that resource
For instance, this script finds the ID for the post with some slug, and updates its meta:
This script repeatedly creates a menu item and sets its ID as parent to another new menu item, thus defining their hierarchy ("Most ancestor menu item"
> "Parent menu item"
> "Child menu item"
):
Gato GraphQL can augment WordPress capabilities for searching for data. As such, we can also use Gato GraphQL to find the data we need, and inject it into WP-CLI.
The following queries will demonstrate how to do that.
Executing a GraphQL query from the terminal
Let's use a GraphQL query to find users with the Spanish locale, and execute a WP-CLI command on that user.
We first limit the result to only 1 user (via pagination: { limit: 1 }
):
In the terminal, we can use curl
(or a similar tool) to execute a query against the GraphQL server, passing the following data:
- Execute the
POST
method - Accepted content type is
application/json
- The body is a dictionary with entry
"query"
and the GraphQL query (and, if needed, also entries"variables"
and"operationName"
) - The query string must be formatted: All
"
must be escaped as\"
, and newlines must be replaced with\n
- Point against the endpoint URL from Gato GraphQL (either the single endpoint, or some custom endpoint)
This prints the response right in the terminal:
Extracting the ID from the GraphQL response
Similar to doing --field=ID
, --format=ids
or --porcelain
in WP-CLI, we need to find a way to extract the specific piece of data that we need from the GraphQL response. In this example, that is the user ID.
We assign the GraphQL response to an environment variable (such as GRAPHQL_RESPONSE
), and identify the user ID with a particular alias (such as spanishLocaleUserID
):
Executing echo $GRAPHQL_RESPONSE
we can visualize the response:
Next, we execute grep
with a regex matching the "spanishLocaleUserID":{ID}
pattern, and extract the ID into environment variable SPANISH_LOCALE_USER_ID
:
Now, we can inject the value of this variable into WP-CLI:
Making the GraphQL query more readable
When formatting the GraphQL query to input it into curl
, it became difficult to read.
A solution is to apply the transformations using bash commands, such as tr
and sed
:
Adding syntax highlighting to the GraphQL query
A further iteration from the previous step is to place the GraphQL query in a separate .gql
file, which can then be edited with an editor (such as VSCode) and use its syntax highlighting:
Then, we read the contents of this file using cat
: