Skip to content

Sortable Filesize Column in Media Library

/* ------------------------------ MEDIA METADATA ------------------------------ */

// edits image meta data
add_action( 'add_attachment', 'my_edit_image_meta_data' );

function my_edit_image_meta_data( $post_ID ) {
    
    // checks if the uploaded file is an image
    if ( wp_attachment_is_image( $post_ID ) ) {

        // finds the total file / image size
        $filesize = filesize( get_attached_file( $post_ID ) );

        // converts bits to mega bytes
        $filesize_convert = $filesize / 1024 / 1024;

        // converts number to format based on locale
        $filesize  = number_format_i18n( $filesize_convert, 3 );

        // creates new meta field with file size of an image
        update_post_meta( $post_ID, '_wp_attachment_image_filesize', $filesize );
    }
}

/* ------------------------------ MEDIA LIBRARY - COLUMNS ------------------------------ */

// creates new columns in media library
add_filter( 'manage_upload_columns', 'my_media_library_columns' );

function my_media_library_columns( $columns ) {
    $columns['filesize'] = __( 'File Size', 'text-domain' );
    
    return $columns;
}

// displays values for each image in specific columns
add_action( 'manage_media_custom_column', 'my_media_library_sizes', 10, 2 );

function my_media_library_sizes( $column, $post_ID ) {
    if ( 'filesize' === $column ) {
        $filesize = get_post_meta( $post_ID, '_wp_attachment_image_filesize', true );

        echo $filesize . __( ' MB', 'text-domain' );
    }
}

// adds sortable function for new columns
add_filter( 'manage_upload_sortable_columns', 'my_media_library_sortable');

function my_media_library_sortable( $columns ) {
    $columns['filesize'] = 'filesize';

    return $columns;
}

// sets sorting for new columns
add_action( 'pre_get_posts', 'my_media_library_sizes_query' );

function my_media_library_sizes_query( $query ) {
    if ( !is_admin() || !$query->is_main_query() ) {
        return;
    }

    $orderby = $query->get( 'orderby' );

    if ( 'filesize' == $orderby ) {

        $meta_query = array(
            'relation' => 'OR',
            array(
                'key' => '_wp_attachment_image_filesize',
                'compare' => 'NOT EXISTS',
            ),
            array(
                'key' => '_wp_attachment_image_filesize',
            ),
        );

        $query->set( 'meta_query', $meta_query );
        $query->set( 'orderby', 'meta_value' );
    }
}

Via

Width and Height Columns: https://wordpress.stackexchange.com/questions/35680/sortable-custom-column-in-media-library

Dieser Beitrag hat 0 Kommentare

Schreibe einen Kommentar

Deine E-Mail wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert

An den Anfang scrollen