NB: Make sure you do a back up of your theme, files and database before attempting the tutorials
Last modified : Nov 18 2021
Estimated reading time : 1 minute, 53 seconds - 132 words
Share the post "Sort by Post Type in WordPress Admin Columns"
With this tutorial, we will show you how to sort post type results in WordPress admin by sorting with a post type meta key in numerical order.
So let’s say for example that you want to sort by ID the job post type from highest to lowest. First, we will need to build the necessary columns for our Job post type.
So here’s to adding our id-job column; make sure to change the post type name.
//////////////////////////////////// Admin columns Informations Post Type ///////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////// add_filter( 'manage_emplois_posts_columns', 'themespress_custom_mycpt_columns' ); function themespress_custom_mycpt_columns( $columns ) { $columns['id-emploi'] = __( 'Id de l'emploi', 'themespress' ); return $columns; }
We will display our results in the column by following the instruction; if we want to add more columns.
add_filter( 'manage_emplois_posts_columns', 'themespress_custom_edit_mycpt_columns' ); function themespress_custom_edit_mycpt_columns( $columns ) { //////////////////////////////////// Admin columns Informations Post Type ///////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////// switch ( $column ) { case 'id-emploi' : // On appelle notre meta key echo get_post_meta( $post_id, 'id-emploi', true ); break; } }
We will now do our parse_query that will enable us to sort our Job ID from highest to lowest. We add a condition “return” if we are not in the WP admin.
add_filter( 'parse_query', 'themespress_custom_post_sort' ); function themespress_custom_post_sort($query) { if ( ! is_admin() ) return $query; global $current_screen; if ( isset( $current_screen ) && 'emplois' === $current_screen->post_type ) { $query->query_vars['orderby'] = 'meta_value'; $query->query_vars['meta_key'] = 'id-emploi'; $query->query_vars['order'] = 'DESC'; } }