Skip to main content

Developing Custom CLI

You can build your own CLI commands using WP-Node CLI. This guide walks you through creating a custom CLI that lists posts with post_type = "page".

📖 Source Code: For a complete working example, see the custom-cli example in the repository.

Initialize a WP-Node Project

First, scaffold your WP-Node project:

npx @rnaga/wp-node-cli -- init

For details, see the Installation Guide

Install CLI Package

Install WP-Node CLI package into your project:

npm i -S @rnaga/wp-node-cli

Create a Custom CLI Command

Create a new file called list-pages.cli.ts:

import { Command } from "commander";

import Application from "@rnaga/wp-node/application";
import { command, subcommand } from "@rnaga/wp-node-cli/decorators";
import { Cli } from "@rnaga/wp-node-cli/cli";

@command("page", { description: "Page commands", version: "1.0.0" })
export class PageCli extends Cli {
@subcommand("list", { description: "List pages" })
async list(program: Command) {
program
.option("-P --perpage <perpage>", "Pages per page")
.option("-S --search <search>", "Search for pages");

await this.settings({ program });

const context = await Application.getContext();
await context.current.assumeUser(this.assumedUserId);

const result = await context.utils.crud.post.list(
{
per_page: this.options.perpage,
search: this.options.search,
},
{
postTypes: ["page"],
}
);

if (!result.data.length) {
this.output("error", "Pages not found");
return;
}

this.output("info", {
message: `Pages found - count: ${result.info.pagination.count}`,
data: result.data,
});

return result;
}
}

Register Your CLI

Update index.ts to register your new CLI to Clis

import "./_wp/settings";
import { Clis } from "@rnaga/wp-node-cli/clis";

import { PageCli } from "./list-pages.cli";

(async () => {
Clis.register([PageCli]);
await Clis.executeCommand(process.argv);
})();

Project File Structure

Your project should look like this:

.
├── _wp
│ ├── config
│ │ ├── index.d.ts
│ │ └── wp.json
│ └── settings.ts
├── .env
├── index.ts # Updated to run CLI
├── list-pages.cli.ts # Your custom CLI file
├── package.json
├── package-lock.json
└── tsconfig.json

Run the Custom CLI

Check that the new command is available:

npx ts-node ./index.ts -- page -h

Output:

Usage: page <subcommand> [options]

Subcommands:
list List pages

Run the actual command:

npx ts-node ./index.ts -- page list -P 1 -Z table -F ID,post_title

Example output:

┌─────────┬────┬───────────────┐
│ (index) │ ID │ post_title │
├─────────┼────┼───────────────┤
│ 0 │ 2 │ 'Sample Page' │
└─────────┴────┴───────────────┘