Halloween Sale 15% off Ends in See the plans
PHP

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.

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

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

  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.