Find the Largest Custom Field Values (WP-CLI)
Adds a "wp largest-meta" command listing the biggest post, user and term meta rows with their key and owner, the quickest way to find plugins bloating the database with huge serialized data.
Opens WPIDE on
Code
if ( ! defined( 'WP_CLI' ) || ! WP_CLI ) {
return;
}
WP_CLI::add_command( 'largest-meta', function ( $args, $assoc_args ) {
global $wpdb;
$tables = array(
'post' => array( $wpdb->postmeta, 'post_id' ),
'user' => array( $wpdb->usermeta, 'user_id' ),
'term' => array( $wpdb->termmeta, 'term_id' ),
);
$which = $assoc_args['table'] ?? 'post';
if ( ! isset( $tables[ $which ] ) ) {
WP_CLI::error( 'Use --table=post, user or term.' );
}
list( $table, $owner ) = $tables[ $which ];
$limit = max( 1, min( 200, (int) ( $assoc_args['limit'] ?? 15 ) ) );
$rows = $wpdb->get_results( $wpdb->prepare(
"SELECT $owner AS owner_id, meta_key, LENGTH(meta_value) AS bytes FROM $table ORDER BY bytes DESC LIMIT %d",
$limit
), ARRAY_A );
foreach ( $rows as &$row ) {
$row['size'] = size_format( (int) $row['bytes'], 1 );
unset( $row['bytes'] );
}
WP_CLI\Utils\format_items( $assoc_args['format'] ?? 'table', $rows, array( 'owner_id', 'meta_key', 'size' ) );
}, array(
'shortdesc' => 'Lists the largest meta rows.',
'synopsis' => array(
array( 'type' => 'assoc', 'name' => 'table', 'optional' => true, 'default' => 'post', 'options' => array( 'post', 'user', 'term' ) ),
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 largest-meta --table=user --limit=20"; read-only.
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.