Last active
October 2, 2019 19:47
-
-
Save davidsword/e1142df3b761454ad5ff06337a105e52 to your computer and use it in GitHub Desktop.
WordPress WPCLI - Count Media Library by Types
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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