Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

Code

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 add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.