# Add a Custom WP-CLI Command

> Registers a "wp site-stats" WP-CLI command that prints counts of posts, pages, comments and users, as a template for your own command-line tools.

- Type: PHP
- Runs: Run everywhere
- Category: [Developer](https://wpide.com/library/category/developer/)
- Tags: wp-cli, cli, automation, tools
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/dev-wp-cli-command/

## Code

```php
if ( defined( 'WP_CLI' ) && WP_CLI && class_exists( 'WP_CLI' ) ) {
    WP_CLI::add_command( 'site-stats', function ( $args, $assoc_args ) {
        $rows = array(
            array( 'item' => 'Published posts', 'count' => (int) wp_count_posts( 'post' )->publish ),
            array( 'item' => 'Published pages', 'count' => (int) wp_count_posts( 'page' )->publish ),
            array( 'item' => 'Approved comments', 'count' => (int) wp_count_comments()->approved ),
            array( 'item' => 'Users', 'count' => (int) count_users()['total_users'] ),
        );

        WP_CLI\Utils\format_items( $assoc_args['format'] ?? 'table', $rows, array( 'item', 'count' ) );
    }, array(
        'shortdesc' => 'Shows basic content statistics for this site.',
        'synopsis'  => array(
            array(
                'type'     => 'assoc',
                'name'     => 'format',
                'optional' => true,
                'default'  => 'table',
                'options'  => array( 'table', 'json', 'csv', 'yaml' ),
            ),
        ),
    ) );
}
```

## Notes

Run "wp site-stats" or "wp site-stats --format=json". The snippet only loads when WP-CLI is running.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Add a Custom WP-CLI Command" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
