i have included 2 custom columns in the metadata of media entries called 'photographer' and 'copyright'. I have included both columns in the admin view of the media library and made them sortable. But when i sort by one of them the results exclude entries with a NULL value in that column
adding custom fields to admin panel media view
//Custom columns in Media Admin view
add_filter('manage_media_columns', 'media_additional_columns', 1);
function media_additional_columns($defaults){
$defaults['photographer'] = __('Photographer');
$defaults['copyright'] = __('Copyright');
return $defaults;
}
//Fill Custom Media Admin Columns with content
add_action('manage_media_custom_column', 'media_custom_columns_attachment_id', 1, 2);
function media_custom_columns_attachment_id($column_name, $post_id){
switch ( $column_name ) {
case 'photographer':
echo get_post_meta( $post_id, 'photographer', true );
break;
case 'copyright':
echo get_post_meta( $post_id, 'copyright', true );
break;
}
}
make custom columns in admin panel media view sortable
//make custom columns sortable
//add custom columns to array sortable columns
add_filter('manage_upload_sortable_columns', 'as_add_custom_column_sortable');
function as_add_custom_column_sortable($columns) {
$columns['photographer'] = 'photographer';
$columns['copyright'] = 'copyright';
return $columns;
}
//alter the post query in case stuff gets sorted by custom columns
add_action( 'pre_get_posts', 'as_custom_column_orderby' );
function as_custom_column_orderby( $query ) {
if( ! is_admin() || ! $query->is_main_query() ) {
return;
}
switch ($query->get( 'orderby')) {
case 'photographer':
$query->set( 'orderby', 'meta_value' );
$query->set( 'meta_key', 'photographer' );
break;
case 'copyright':
$query->set( 'orderby', 'meta_value' );
$query->set( 'meta_key', 'copyright' );
break;
}
}
I want to include the entries with NULL value in the sorted table, after the entries with non-NULL values.
I have found this post that answers the same question for the Posts and for Users. I thought the answer applicable for Posts would work also for media since media are basically posts of the type attachment but it doesnt, my media library turns up completely empty.
I am just starting with php, help would be much appreciated!