Hooks for admin colomn
Wordpress default Post
add_filter( 'manage_post_posts_columns', 'callback_function' );add_action( 'manage_post_posts_custom_column', 'callback_function', 10, 2 );
Other Custom Post types
add_filter( 'manage_{post_type}_posts_columns', 'callback_function' );
add_action( 'manage_{post_type}_custom_column', 'callback_function', 10, 2 );
Example: For student post type
function my_custom_columns_list($columns) {
$columns['address'] = 'Address';
return $columns;
}
add_filter( 'manage_student_posts_columns', 'my_custom_columns_list' );
add_action( 'manage_student_posts_custom_column', 'hs_screen_content', 10, 2 );
function hs_screen_content( $column_name, $post_id ) {
if( $column_name == 'address' ) {
echo get_post_meta( $post_id, 'address', true );
}
}
Adding sortable feature
1. Adding a sortable feature
hooks : manage_edit-{post_type}_sortable_columns
add_filter("manage_edit-student_sortable_columns", "add_sort_post");
function add_sort_post($cols) {
$cols['address'] = 'address';
return $cols;
}
2. Adding sort option to query
add_action( 'pre_get_posts', 'wp_sort_test_col' );
function wp_sort_test_col( $query ) {
if ( $query->is_main_query() && $query->get( 'orderby' ) === 'address' ) {
$query->set( 'meta_key', 'address' ); //value of field
$query->set( 'orderby', 'meta_value_num' );
//meta_value_num if field has numeric value
//meta_value for other string value
}
}
For colomn filter
We have to do 2 things
1. Add dropdown select filter list
2. Manage query for selected option
1. Add dropdown for filter
add_action( 'restrict_manage_posts', 'wp_admin_posts_filter_restrict_manage_posts' );
function wp_admin_posts_filter_restrict_manage_posts(){
$type = 'post';
if (isset($_GET['post_type'])) {
$type = $_GET['post_type'];
}
//only add filter to post type you want
if ('student' == $type){
$html = ' <select name="address">'; //filter colomn name
$current = isset($_GET['address'])? $_GET['address']:"";
foreach ($filterdata $key => $data) {
$label = $data['name];
$value = $data['code'];
$html .= sprintf('<option value="%s"%s>%s</option>',
$value,
$value === $current? ' selected="selected"':'',
$label
);
}
$html .= '</select>';
echo $html;
}
}
2. Add query for filter
add_filter( 'parse_query', 'wp_posts_filter' );
function wp_posts_filter( $query ){
global $pagenow;
$type = 'post';
if (isset($_GET['post_type'])) {
$type = $_GET['post_type'];
}
if ( 'student' == $type && is_admin() && $pagenow=='edit.php' && !empty($_GET['address']) ){
$query->query_vars['meta_key'] = 'address'; //field name
$query->query_vars['meta_value'] = $_GET['address']; //value for search
}
}