Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Create a sortable admin column for attachment (Media Library) file size. See https://cfxdesign.com/display-file-size-as-a-sortable-column-in-the-media-library/
<?php
// Adds initial meta to each attachment
function add_initial_file_size_postmeta($column_name, $post_id) {
static $query_ran;
if($query_ran !== null) {
$all_imgs = new WP_Query(array(
'post_type' => 'attachment',
'post_status' => 'inherit',
'posts_per_page' => -1,
'fields' => 'ids'
));
$all_imgs_array = $all_imgs->posts;
foreach($all_imgs_array as $a) {
if(!get_post_meta($a, 'filesize', true)) {
$file = get_attached_file($a);
update_post_meta($a, 'filesize', filesize($file));
}
}
$query_ran = true;
}
}
add_action('manage_media_custom_column', __NAMESPACE__.'\\add_initial_file_size_postmeta');
<?php
// Ensure file size meta gets added to new uploads
function add_filesize_metadata_to_images($meta_id, $post_id, $meta_key, $meta_value) {
if('_wp_attachment_metadata' == $meta_key) {
$file = get_attached_file($post_id);
update_post_meta($post_id, 'filesize', filesize($file));
}
}
add_action('added_post_meta', 'add_filesize_metadata_to_images', 10, 4);
// Add the column
function add_column_file_size($posts_columns) {
$posts_columns['filesize'] = __('File Size');
return $posts_columns;
}
add_filter('manage_media_columns', 'add_column_file_size');
// Populate the column
function add_column_value_file_size($column_name, $post_id) {
if('filesize' == $column_name) {
if(!get_post_meta($post_id, 'filesize', true)) {
$file = get_attached_file($post_id);
$file_size = filesize($file);
update_post_meta($post_id, 'filesize', $file_size);
} else {
$file_size = get_post_meta($post_id, 'filesize', true);
}
echo size_format($file_size, 2);
}
return false;
}
add_action('manage_media_custom_column', 'add_column_value_file_size', 10, 2);
// Make column sortable
function add_column_sortable_file_size($columns) {
$columns['filesize'] = 'filesize';
return $columns;
}
add_filter('manage_upload_sortable_columns', 'add_column_sortable_file_size');
// Column sorting logic (query modification)
function sortable_file_size_sorting_logic($query) {
global $pagenow;
if(is_admin() && 'upload.php' == $pagenow && $query->is_main_query() && !empty($_REQUEST['orderby']) && 'filesize' == $_REQUEST['orderby']) {
$query->set('order', 'ASC');
$query->set('orderby', 'meta_value_num');
$query->set('meta_key', 'filesize');
if('desc' == $_REQUEST['order']) {
$query->set('order', 'DSC');
}
}
}
add_action('pre_get_posts', 'sortable_file_size_sorting_logic');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment