wordpress - custom column for custom post type


Keywords:wordpress 


Question: 

I have this code below to create a custom post type.

function custom_post_type() {
    register_post_type('multi-step-form', array(
    'supports' => array('title'),
    'public' => false,
    'show_ui' => true,
    'labels' => array(
      'name' => 'Multi-Step Forms',
      'add_new_item' => 'Add New Multi-Step Form',
      'edit_item' => 'Edit Multi-Step Form',
      'all_items' => 'All Multi-Step Forms',
      'singular_name' => 'Multi-Step Form'
    ),
    'menu_icon' => 'dashicons-universal-access-alt',
  ));               
}   

add_action( 'init',  'custom_post_type');   

How can I add a custom column like its their ID or slug in the mange post type screen?

Please see screenshot:

enter image description here

Thanks in advanced!


2 Answers: 

try this

add_filter('manage_posts_columns', 'default_columns_head');

function default_columns_head($defaults) {
    global $current_screen;
    if (in_array($current_screen->post_type, array('multi-step-form','other_post_type'))) {
        $defaults['col1'] = 'col1 name';
        $defaults['col2'] = 'col2 name';
    }
    return $defaults;
}
function default_columns_content($column_name, $post_ID) {

    if ($column_name == 'col1') {
        $post = get_post($post_ID);
       echo 'col 1 data';
    } elseif ($column_name == 'col2') {
         $post = get_post($post_ID);
        echo 'col2 data';
    }
}

add_action('manage_posts_custom_column', 'default_columns_content', 10, 2);
 

This should display custom columns only for your custom post type and not other post types.

add_filter('manage_multi-step-form_columns', 'my_custom_post_columns');

function my_custom_post_columns($columns) {
    $columns['post-id'] = 'Post ID';
    $columns['post-slug'] = 'Post Slug';

    return $columns;
}

add_action('manage_multi-step-form_custom_column',  'show_my_custom_columns');

function show_my_custom_columns( $name ) {
    global $post;

    switch ($name) {
        case 'post-id':
            echo $post->ID;
            break;
        case 'post-slug':
            echo $post->post_name;
            break;
    }
}