Custom Post Type with Taxonomy

Posts and pages are two sides of the same coin, the main difference is that posts (a.k.a blog-posts) are sorted by date and have optional categories or tags, pages do not.

Under the hood they are both called post_types but they have been initialized with different parameters.

We will be creating our own post type with it’s own taxonomy (categories) for storing favourite music videos.

Create a new plugin

# nvim wp-content/plugins/music-ctp.php
<?php
/*
 * @package Music Custom Posttype
 * @version 1.0
 * Plugin Name: Music Custom Posttype
 * Description: Custom posttype for music videos
 * Version: 1.0
 * Author: Nimpen, ASBRA AB
 * Author URI: http://asbra.nu
 */


/**
 * Create Custom Post Type
 */
function music_posttype($posttype)
{
	$posttype = 'music'; // Name in Database

	$labels = array(
		'name'          => __('Music posts'),
		'singular_name' => __('Music post')
	);

	$attr = array(
		'labels'        => $labels,
		'supports'      => array( 'title', 'editor', 'excerpt', 'author', 'thumbnail', 'comments', 'revisions', 'custom-fields', ),
		'public'        => true,
		'has_archive'   => true,
		'menu_position' => 1,
	);

	register_post_type( $posttype, $attr);
}
add_action( 'init', 'music_posttype' );

/**
 * Create a Custom Taxonomy for Custom Post Type
 */
function music_taxonomy() {
    register_taxonomy(
        'music_categories',  // Name of taxonomy 
        'music',             // Name of post type
        array(
            'hierarchical' => true,
            'label' => 'Music Categories',  //Display name
            'query_var' => true,
        )
    );
}
add_action( 'init', 'music_taxonomy');

After you’ve enabled or disabled a custom post type or a custom taxonomy be sure to put the following command at the end of your functions file and run once:

flush_rewrite_rules();

Otherwise your webpage will state something like “Ooops! this is a stupid message”