Skip to content

Instantly share code, notes, and snippets.

@davidsword
Last active October 2, 2019 19:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidsword/e1142df3b761454ad5ff06337a105e52 to your computer and use it in GitHub Desktop.
Save davidsword/e1142df3b761454ad5ff06337a105e52 to your computer and use it in GitHub Desktop.
WordPress WPCLI - Count Media Library by Types
<?php
/**
* Implements `media-count` command.
*/
class WPCLI_Media_Library_Count {
/**
* Get total count of all media and break down counts for each media type.
*
* ## EXAMPLES
*
* wp media-count
*
* @when after_wp_load
*/
function __invoke() {
global $wpdb;
$total = 0;
$types = $wpdb->get_results( "SELECT DISTINCT post_mime_type FROM $wpdb->posts" );
if ( ! $types ) {
WP_CLI::error( "Unable to find any post_mime_types" );
}
foreach ( $types as $k => $type ) {
if ( empty( $type->post_mime_type ) ) {
continue;
}
$count = (int) $wpdb->get_var( $wpdb->prepare( "
SELECT COUNT(*)
FROM $wpdb->posts
WHERE post_type = 'attachment'
AND post_mime_type = '%s'
", $type->post_mime_type ) );
WP_CLI::line( $count . " - " . $type->post_mime_type );
$total += $count;
}
WP_CLI::success( "Total Media Counted: " . $total );
}
}
WP_CLI::add_command( 'media-count', 'WPCLI_Media_Library_Count' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment