Make File Size?and?Post columns sortable
-
Sortable Columns in Media Library and Post List
This code makes specific columns, such as File Size and Post ID, sortable in both the media library and the post list in WordPress. It also handles the sorting logic based on these columns.Key Functions:
- Make Columns Sortable:
- Adds?File Size?and?Post ID?as sortable columns in both the media library and the post list.
- Handle Sorting by Columns:
- Modifies the query to allow sorting by the custom columns (File Size?and?Post ID) in ascending or descending order.
/**
* Make specific columns sortable in the media library and post list.
*
* This function adds custom columns to the sortable columns list for both
* media library and post list in the WordPress admin.
*/
function asenha_make_columns_sortable($sortable_columns) {
// Add custom sortable columns for file size and post ID (removed media extension)
$sortable_columns['asenha-file-size'] = 'asenha-file-size';
$sortable_columns['asenha-id'] = 'asenha-id';
return $sortable_columns;
}
// Apply the filter to make columns sortable in both the media library and posts
add_filter('manage_upload_sortable_columns', 'asenha_make_columns_sortable');
add_filter('manage_edit-post_sortable_columns', 'asenha_make_columns_sortable');
/**
* Handle sorting by custom columns (file size and post ID).
*
* This function modifies the query to handle sorting for custom columns,
* including file size and post ID.
*/
function asenha_sort_columns_sortable($query) {
// Ensure we're modifying the admin query and the main query
if (!is_admin() || !$query->is_main_query()) {
return;
}
// Get the 'orderby' and 'order' parameters from the query
$orderby = $query->get('orderby');
$order = $query->get('order');
// Handle sorting for the custom 'file size' column
if ($orderby === 'asenha-file-size') {
$query->set('order', $order === 'asc' ? 'ASC' : 'DESC');
}
// Handle sorting for the custom 'post ID' column
if ($orderby === 'asenha-id') {
$query->set('order', $order === 'asc' ? 'ASC' : 'DESC');
}
}
// Apply the sorting logic for custom columns
add_action('pre_get_posts', 'asenha_sort_columns_sortable'); - Make Columns Sortable:
Viewing 1 replies (of 1 total)
Viewing 1 replies (of 1 total)
- You must be logged in to reply to this topic.