完整工作代码
/*
* Add Sortable Width and Height Columns to the Media Library
*
*/
if( is_admin() )
{
add_filter( \'manage_upload_columns\', \'wpse_35680_size_columns_register\' );
add_action( \'manage_media_custom_column\', \'wpse_35680_size_columns_display\', 10, 2 );
add_filter( \'manage_upload_sortable_columns\', \'wpse_35680_size_columns_sortable\' );
add_filter( \'wp_generate_attachment_metadata\', \'wpse_35680_update_imagesize_meta_data\', 10, 2);
add_action( \'pre_get_posts\', \'wpse_35680_size_columns_do_sort\' );
}
/*
* Adding Width and Height columns
*
*/
function wpse_35680_size_columns_register( $columns )
{
$columns[\'_width\'] = \'Width\';
$columns[\'_height\'] = \'Height\';
return $columns;
}
/*
* Display the columns
*
*/
function wpse_35680_size_columns_display( $column_name, $post_id )
{
if( \'_width\' != $column_name && \'_height\' != $column_name || !wp_attachment_is_image( $post_id ) )
return;
list( $url, $width, $height ) = wp_get_attachment_image_src( $post_id, \'full\' );
if( \'_width\' == $column_name )
echo get_post_meta($post_id, \'_width\', true);
if( \'_height\' == $column_name )
echo get_post_meta($post_id, \'_height\', true);
}
/*
* Registering columns as sortable
*
*/
function wpse_35680_size_columns_sortable( $columns )
{
$columns[\'_width\'] = \'_width\';
$columns[\'_height\'] = \'_height\';
return $columns;
}
/*
* Save Image Attachments meta data on save
*
*/
function wpse_35680_update_image_meta_data( $image_data, $att_id )
{
$width = $image_data[\'width\'];
$height = $image_data[\'height\'];
update_post_meta( $att_id, \'_width\', $width );
update_post_meta( $att_id, \'_height\', $height );
return $image_data;
}
/*
* Sort the columns
*
*/
function wpse_35680_size_columns_do_sort(&$query)
{
global $current_screen;
if( \'upload\' != $current_screen->id )
return;
$is_width = (isset( $_GET[\'orderby\'] ) && \'_width\' == $_GET[\'orderby\']);
$is_height = (isset( $_GET[\'orderby\'] ) && \'_height\' == $_GET[\'orderby\']);
if( !$is_width && !$is_height )
return;
if ( \'_width\' == $_GET[\'orderby\'] )
{
$query->set(\'meta_key\', \'_width\');
$query->set(\'orderby\', \'meta_value_num\');
}
if ( \'_height\' == $_GET[\'orderby\'] )
{
$query->set(\'meta_key\', \'_height\');
$query->set(\'orderby\', \'meta_value_num\');
}
}
更新Posts表中所有图像的变通方法
/*
* Update ALL attachments metada with Width and Height
*
* Important: Run Only Once
*
*/
//add_action(\'admin_init\',\'wpse_35680_run_only_once\');
function wpse_35680_run_only_once()
{
global $wpdb;
$attachments = $wpdb->get_results( "SELECT ID FROM $wpdb->posts WHERE post_mime_type LIKE \'%image%\'" );
foreach( $attachments as $att )
{
list( $url, $width, $height ) = wp_get_attachment_image_src( $att->ID, \'full\' );
update_post_meta( $att->ID, \'_width\', $width );
update_post_meta( $att->ID, \'_height\', $height );
}
}
整个堆栈汇集了来自Rarst、Bainternet、kaiser、t31os和scribu的宝贵信息