Add Custom Columns To Post Type

WordPressPosted on

1 min read

Declaring a new admin column in our WordPress admin’s list pages is a common task. Fortunately, we can do it quickly.

To create new columns for a WP post type of custom post type, we need two filters:

One usual case is when we create a custom post type and add a custom taxonomy to it. Our taxonomy not appended to the admin columns automatically, so we need to declare it like the following:

// Add the Terms(s) columns to the snippets post type
function set_custom_edit_snippets_columns($columns) {
    $columns['terms'] = __( 'Term(s)', 'pine' );
    return $columns;
}
add_filter( 'manage_snippets_posts_columns', 'set_custom_edit_snippets_columns' );
// Add the data to the snippet's Term(s) column
function custom_snippets_column( $column, $post_id ) {
    switch ( $column ) {
        case 'terms' :
            $terms = get_the_terms( $post_id, 'snippets_category' );
            $links = array();
        
            foreach ( $terms as $term ) {
                $link = get_term_link( $term, 'snippets_category' );
                if ( is_wp_error( $link ) ) {
                    return $link;
                }
                $links[] = '<a href="' . admin_url( 'edit.php?post_type=snippets&snippets_category=' . $term->slug ) . '" rel="tag">' . $term->name . '</a>';
            }
            $terms = join( ', ', $links );
            if ( is_string( $terms ) )
                echo $terms;
            else
                _e( 'No avialable term.', 'pine' );
            break;
    }
}
add_action( 'manage_snippets_posts_custom_column' , 'custom_snippets_column', 10, 2 );
Note if you register your post types in a plugin it is most likely that you have a switch to turn on this behavior.

Need a web developer? Maybe we can help, get in touch!

Looking for web dev job?
You can check them on Jooble.

To see and write comments, you must allow the related (Disqus) cookies. For more information, please visit our privacy policy page.

Similar Posts

More content in WordPress category