Add Taxonomy to Custom Post Type

I use Custom Post Types a lot at work, and taxonomies are a great way to help organize and control their display on Category and Custom Template pages.

/**** Register Custom Post types ***/
add_action( 'init', 'create_post_type' );
function create_post_type() {

// register testimonial post type start
        $labels = array(
	     'name' => _x('Testimonials', 'Testimonials'),
	     'singular_name' => _x('Testimonial', 'Testimonial'),
	     'add_new' => _x('Add Testimonial', 'Testimonial'),
	     'add_new_item' => __('Add Testimonial'),
	     'edit_item' => __('Edit Testimonial'),
	     'new_item' => __('New Testimonial'),
	     'all_items' => __('All Testimonials'),
	     'view_item' => __('View Testimonial'),
	     'search_items' => __('Search Testimonials'),
	     'not_found' =>  __('No Testimonials found'),
	     'not_found_in_trash' => __('No Testimonials found in Trash'), 
	     'parent_item_colon' => '',
	     'menu_name' => __('Testimonials')
	);
		$args = array(
		'labels' => $labels,
		'taxonomies' => array('testimonial_type'), // must match taxonomy rewrite slug
		'public' => true,
		'publicly_queryable' => true,
		'show_ui' => true, 
		'show_in_menu' => true, 
		'query_var' => true,
		'rewrite' => true,
		'capability_type' => 'post',
		'has_archive' => true, 
		'hierarchical' => true,
		'menu_position' => null,
		'supports' => array( 'title', 'thumbnail','revisions', 'custom-fields' ),
                'exclude_from_search' => true, // control display in search pages
                'taxonomy' => array('testimonial_category') // link to taxonomy function
	); 
	register_post_type('testimonial',$args);
	// register testimonial post type end
}

// add taxonomy to testimonial post type
function testimonial_type() { // must match init function call
	register_taxonomy( // repeat and update this block within the function to create more taxonomies!
		'testimonial_type', // must match rewrite slug
		array('testimonial'), // match custom post type slug
		array(
			'label' => __( 'Type' ),
			'rewrite' => array( 'slug' => 'testimonial_type' ),
			'hierarchical' => true,
			'query_var' => true
		)
	);
}
add_action ( 'init', 'testimonial_type' );

Leave a Reply

katherine as a flat graphic icon

About Me

I’m an African / Ojibwe First Nations Web Developer living in Winnipeg, Manitoba.

Visit the Tips and Blog to see what I’m working on.