Skip to content Skip to sidebar Skip to footer
Reading Time: 2 minutes

When you’re creating custom post types into your wordpress site you can see it’s posts as list.But there is no option to sort each columns.You have to manually add this facility to do this.I’ll describe here very simply how to do this without any plugin.

wordpress sort custom post type columns

How to add custom post type columns?

I’ll first show you how to add custom columns.Then you can understand the post better.
My custom post type is “Campaigns“.


// define custom columns
add_filter( 'manage_edit-campaigns_columns', 'wpli_edit_campaigns_columns' ) ;
function wpli_edit_campaigns_columns( $columns ) {
	$columns = array(
		'cb' => '',
		'title' => __( 'Campaign Name' ),
		'campaign_status' => __( 'Status' ), // my custom meta value
		'campaign_user_name' => __( 'User' ), // my another custom meta value
		'date' => __( 'Date' )
	);
	return $columns;
}


// display custom columns
add_action( 'manage_campaigns_posts_custom_column', 'wpli_campaigns_columns', 10, 2 );
function wpli_campaigns_columns( $column, $post_id ) {
	global $post;
	switch( $column ) {
 		case 'campaign_status' :
  			 $campaign_status = get_post_meta( $post_id, 'campaign_status', true ); // my custom meta value
  			 echo $campaign_status;
 			 break;

 		case 'campaign_user_id' :
  			 $campaign_user_name = get_post_meta( $post_id, 'campaign_user_name', true ); // my another custom meta value will show
   			 echo $campaign_user_name;
 			break;

 		default :
			break;
	}
}

Sort custom post type columns


add_filter( 'manage_edit-campaigns_sortable_columns', 'wpli_campaigns_sortable_columns' );
function wpli_campaigns_sortable_columns( $columns ) {
	$columns['campaign_status'] = 'campaign_status';  // add your custom meta value
	$columns['campaign_user_name'] = 'campaign_user_name';  // add your custom meta value
	return $columns;
}

add_action( 'load-edit.php', 'wpli_edit_campaigns_load' );
function wpli_edit_campaigns_load() {
	add_filter( 'request', 'wpli_sort_campaigns' );
}

function wpli_sort_campaigns( $vars ) {
 	if ( isset( $vars['post_type'] ) && 'campaigns' == $vars['post_type'] ) { // check the post type
 		//  "campaign_status" custom meta value for sort
		if ( isset( $vars['orderby'] ) && 'campaign_status' == $vars['orderby'] ) {
 			$vars = array_merge(
				$vars,
				array(
					'meta_key' => 'campaign_status', // add your custom meta value
					'orderby' => 'meta_value_num'
				)
			);
		}

		//  "campaign_user_name" custom meta value for sort
		if ( isset( $vars['orderby'] ) && 'campaign_user_name' == $vars['orderby'] ) {
 			$vars = array_merge(
				$vars,
				array(
					'meta_key' => 'campaign_user_name', // add your another custom meta value
					'orderby' => 'meta_value_num'
				)
			);
		}
	}
	return $vars;
}

After add that you can sort the columns.
wordpress sort custom post type column
Hope this will help to your custom plugin.