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.
Opens WPIDE on
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
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.