WordPress: How to get all the categories for a custom post type

Getting your Trinity Audio player ready...

Scenario: You need to get all the categories to make a list.

Goal: Create a navigation list of all the categories for a custom post type.

Difficulty: Easy

Coding Required: Yes

Here are the starting arguments for your function:


/**
	 * Get all categories or custom taxonomy from a post type
	 *
	 * Ex: [ws-category-list] - get all post categories
	 * Ex: [ws-category-list post_type="apple"] - get all categories from the "apple" post type
	 * Ex: [ws-category-list post_type="apple" taxonomy="color"] - get all terms from the "color" taxonomy from the "apple" post type
	 *
	 * @param array $atts
	 *
	 * @return string|void
	 */

	function ws_get_custom_post_type_categories( $atts ) {

		$atts = shortcode_atts( array(
			'post_type'   =>'apple', // custom post type named apple
			'taxonomy' => 'category', // name of taxonomy associated with apple
			'hide_empty' => false, // show categories even if they are empty
			'number'  => 5, // number of categories to show
		), $atts, 'wd-category-list' );
		
		$apple_categories = get_terms( $atts );		
		
		if ( ! $apple_categories ) {
			return;
		}

		$output .= '<ul>';

		foreach( $apple_categories as $apple_category){ 
			$output .= '<li><a href="' . get_term_link($apple_category->term_id) . '">' . $apple_category->name . '</a></li>';
		}

		$output .= '</ul>';

		return $output; 
	} 

	add_shortcode('wd-category-list', 'ws_get_custom_post_type_categories');
	

This shortcode will display all categories in a list for the custom post type “apple”.