Register Taxonomy
Suppose you created a Custom Post Type(CPT) named Portfolio and need a taxonomy for it named Project Type, Then code is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
//hook into the init action and call create_book_taxonomies when it fires add_action( 'init', 'create_subjects_hierarchical_taxonomy', 0 ); //create a custom taxonomy name it subjects for your posts function create_subjects_hierarchical_taxonomy() { // Add new taxonomy, make it hierarchical like categories //first do the translations part for GUI $labels = array( 'name' => _x( 'Project Type', 'taxonomy general name' ), 'singular_name' => _x( 'Project Type', 'taxonomy singular name' ), 'search_items' => __( 'Search Category' ), 'all_items' => __( 'All Categories' ), 'parent_item' => __( 'Parent Categories' ), 'parent_item_colon' => __( 'Parent Category:' ), 'edit_item' => __( 'Edit Category' ), 'update_item' => __( 'Update Category' ), 'add_new_item' => __( 'Add New Category' ), 'new_item_name' => __( 'New Project Type' ), ); // Now register the taxonomy register_taxonomy('project-type',array('portfolio'), array( 'hierarchical' => true, 'labels' => $labels, 'show_ui' => true, 'show_in_rest' => true, 'show_admin_column' => true, 'query_var' => true, 'rewrite' => array( 'slug' => 'subject' ), )); } |
Get custom template part if custom taxonomy
In your archive.php file, you will find ‘get_template_part( ‘template-parts/content’, get_post_format();‘. Replace it by following code:
1 2 3 4 5 |
if ( has_term( '', 'custom_taxonomy' ) ) { get_template_part( 'template-parts/content', 'portfolio' ); } else { get_template_part( 'template-parts/content', get_post_format() ); } |
Custom CPT Category / Taxonomy Listing
You can use it in any page template or archive page.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
$args = array( 'taxonomy' => 'project-type', 'order' => 'ASC' ); $categories = get_categories($args); echo '<ul>'; foreach ($categories as $category) { $url = get_term_link($category);?> <li><a href="<?php echo $url;?>"><?php echo $category->name; ?></a></li> <?php } echo '</ul>'; |