Site icon StartFunction

Add columns for custom taxonomies to custom post types in WordPress

If you ever found strange that you could edit the terms of a custom taxonomy for a custom post type using the Quick Edit link but you couldn’t see the terms applied in the columns, you’re not alone. That’s why in this tutorial we will learn how to display those terms in the list view for our custom post types.

In the same way that you see Tags and Categories in the posts list view, it is also useful to know which terms have been applied for our custom taxonomies in our custom post types. But even for regular posts, custom taxonomies are now shown. The code below utilizes a fictional custom post type ‘event‘ and a custom taxonomy ‘events‘ and creates a new column in the event list view to display the events custom taxonomy with links for each term to display a filtered view of events. You can add this code in the functions.php file of your WordPress theme or, if you have it, in a dedicated page for the admin.

We first hook a functions to filter the columns and add our own column, and then hook another function to display the taxonomy terms for each event post:

[php]
add_filter( ‘manage_event_posts_columns’, ‘ilc_cpt_columns’ );
add_action(‘manage_event_posts_custom_column’, ‘ilc_cpt_custom_column’, 10, 2);
[/php]

The first function used for filtering is pretty easy, we simply add a new column for our taxonomy and set a label for the column header:

[php]
function ilc_cpt_columns($defaults) {
$defaults[‘events’] = ‘Event Type’;
return $defaults;
}
[/php]

Now, after getting the post terms by its taxonomy, we initialize an array containing all the terms and build the links for each term using the post type and the term slug. If some post doesn’t have any terms, we display a notice:

[php]
function ilc_cpt_custom_column($column_name, $post_id) {
$taxonomy = $column_name;
$post_type = get_post_type($post_id);
$terms = get_the_terms($post_id, $taxonomy);

if ( !empty($terms) ) {
    foreach ( $terms as $term )
        $post_terms[] = "<a href='edit.php?post_type={$post_type}&{$taxonomy}={$term->slug}'> " . esc_html(sanitize_term_field('name', $term->name, $term->term_id, $taxonomy, 'edit')) . "</a>";
    echo join( ', ', $post_terms );
}
else echo '<i>No terms.</i>';

}
[/php]

And that’s it, your custom post types will now display their custom taxonomies and their assigned terms. If you need to add more columns for taxonomies, just add them in the $defaults array in the ilc_cpt_columns function.

Exit mobile version