WordPress – How to add custom column to Custom Post Type posts list

The following code shows how to add a custom column to a Custom Post Type in WordPress.

In this example we’ll be adding a “Usefulness” column – and populating it with data from the post meta data (_ht_kb_usefulness). This column will also be sortable.

To apply this to your website you need to know the Custom Post Type slug – this can be found by opening the posts list and looking at ‘post_type’ variable.

In this example the slug is ht_kb – you will need to replace this in the code below with your slug.

You will also need to customise the script to use the details you need to be used in the column.

// Add the custom column to the post type -- replace ht_kb with your CPT slug
add_filter( 'manage_ht_kb_posts_columns', 'itsg_add_custom_column' );
function itsg_add_custom_column( $columns ) {
    $columns['usefulness'] = 'Usefulness';

    return $columns;
}

// Add the data to the custom column -- replace ht_kb with your CPT slug
add_action( 'manage_ht_kb_posts_custom_column' , 'itsg_add_custom_column_data', 10, 2 );
function itsg_add_custom_column_data( $column, $post_id ) {
    switch ( $column ) {
        case 'usefulness' :
            echo get_post_meta( $post_id , '_ht_kb_usefulness' , true ); // the data that is displayed in the column
            break;
    }
}

// Make the custom column sortable -- replace ht_kb with your CPT slug
add_filter( 'manage_edit-ht_kb_sortable_columns', 'itsg_add_custom_column_make_sortable' );
function itsg_add_custom_column_make_sortable( $columns ) {
	$columns['usefulness'] = 'usefulness';

	return $columns;
}

// Add custom column sort request to post list page
add_action( 'load-edit.php', 'itsg_add_custom_column_sort_request' );
function itsg_add_custom_column_sort_request() {
	add_filter( 'request', 'itsg_add_custom_column_do_sortable' );
}

// Handle the custom column sorting
function itsg_add_custom_column_do_sortable( $vars ) {

	// check if post type is being viewed -- replace ht_kb with your CPT slug
	if ( isset( $vars['post_type'] ) && 'ht_kb' == $vars['post_type'] ) {

		// check if sorting has been applied
		if ( isset( $vars['orderby'] ) && 'usefulness' == $vars['orderby'] ) {

			// apply the sorting to the post list
			$vars = array_merge(
				$vars,
				array(
					'meta_key' => '_ht_kb_usefulness',
					'orderby' => 'meta_value_num'
				)
			);
		}
	}

	return $vars;
}

Was this article helpful?

Related Articles