Skip to content

Instantly share code, notes, and snippets.

@angelorocha
Created June 11, 2021 19:27
Show Gist options
  • Save angelorocha/8a2579f08af11d3b5463f376dc290732 to your computer and use it in GitHub Desktop.
Save angelorocha/8a2579f08af11d3b5463f376dc290732 to your computer and use it in GitHub Desktop.
WordPress - Make post meta column sortable
<?php
/**
* Usage: cpt_make_sortable_column('post_type', array('coluna'));
*
* @param string $post_type
* @param array $columns
*/
function cpt_make_sortable_column(string $post_type, array $columns = []){
$filter = "manage_edit-{$post_type}_sortable_columns";
add_filter($filter, function ($sortable_columns) use ($columns){
foreach($columns as $column){
$sortable_columns[$column] = $column;
}
return $sortable_columns;
});
add_action('pre_get_posts', function ($query) use ($columns){
foreach($columns as $column){
if($query->is_main_query() && $query->get('orderby') === $column){
$query->set('meta_key', $column);
$query->set('orderby', 'meta_value');
}
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment