Created
June 11, 2021 19:27
-
-
Save angelorocha/8a2579f08af11d3b5463f376dc290732 to your computer and use it in GitHub Desktop.
WordPress - Make post meta column sortable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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