NB: Make sure you do a back up of your theme, files and database before attempting the tutorials

Sort by Post Type in Wordpress Admin Columns
Easy

---- Last modified : Nov 18 2021

Estimated reading time : 1 minute, 53 seconds - 132 words

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';
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>