Find the Heaviest Posts by Content Size (WP-CLI)
Adds a "wp heaviest-posts" command listing the posts and pages with the largest stored content, revisions excluded, to track down pasted base64 images or page builder bloat slowing the editor.
Opens WPIDE on
Code
if ( ! defined( 'WP_CLI' ) || ! WP_CLI ) {
return;
}
WP_CLI::add_command( 'heaviest-posts', function ( $args, $assoc_args ) {
global $wpdb;
$limit = max( 1, min( 200, (int) ( $assoc_args['limit'] ?? 15 ) ) );
$rows = $wpdb->get_results( $wpdb->prepare(
"SELECT ID, post_type, post_status, post_title, LENGTH(post_content) AS bytes, post_content LIKE '%%data:image/%%' AS has_base64 FROM {$wpdb->posts}
WHERE post_type NOT IN ('revision','attachment','nav_menu_item','customize_changeset') ORDER BY bytes DESC LIMIT %d",
$limit
), ARRAY_A );
foreach ( $rows as &$row ) {
$row['size'] = size_format( (int) $row['bytes'], 1 );
$row['base64_img'] = $row['has_base64'] ? 'yes' : 'no';
unset( $row['bytes'], $row['has_base64'] );
}
WP_CLI\Utils\format_items( $assoc_args['format'] ?? 'table', $rows, array( 'ID', 'post_type', 'post_status', 'size', 'base64_img', 'post_title' ) );
}, array(
'shortdesc' => 'Lists posts with the largest content.',
'synopsis' => array(
array( 'type' => 'assoc', 'name' => 'limit', 'optional' => true, 'default' => 15 ),
array( 'type' => 'assoc', 'name' => 'format', 'optional' => true, 'default' => 'table', 'options' => array( 'table', 'csv', 'json' ) ),
),
) );
Notes
Example "wp heaviest-posts --limit=20 --format=csv".
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.