Create a hierarchical Custom Post Type in WordPress

Creating a hierarchical custom post type is not difficult but it has one trick. Besides you need to set hierarchical to true. You must also add supports array support for ‘page-attributes’. Without this page-attributes menu won’t appear in backend and you can’t give your post a parent. I struggle to figure this out for a while.

Here’s a code to add to your functions.php or plugin.

//BOOKS HIERARCHICAL POST TYPE


function xiong_register_books_post_type () {

    //Variables
    $singular = 'Book';
    $plural = 'Books';
    $object = 'book';
    $labels = array(
    'name'                  => $plural, 
    'singular_name'         => $singular,
    'add_name'              => 'Add new',
    'add_new_item'          => 'Add new ' . $singular,
    'edit'                  => 'Edit',
    'edit_item'             => 'Edit ' . $object,
    'new_item'              => 'New ' .$singular,
    'view'                  => 'Show ' . $singular,
    'view_item'             => 'Show ' . $singular,
    'search_term'           => 'Search ' . $object,
    'not_found'             => 'Could not find that ' . $object,  
    'not_found_in_trash'    => 'Could not find that ' . $object . ' from trash'

    );

    $args = array(
    'labels'    => $labels,
    'public'    => true,
    'publicly_queryable' => true,
    'exclude_from_search'=> false,
    'show_ui'            => true,
    'show_in_menu'       => true,
    'show_in_admin_bar'  => true,
    'menu_position'      => 20,
    'menu_icon'          => 'dashicons-book',
    'can_export'         => true,
    'delete_with_user'   => false,
    'hierarchical'       => true, //IMPORTANT!!!
    'has_archive'        => true, 
    'query_var'          => true,
    'capability_type'    => 'page',
    'map_meta_cap'       => true,
    'rewrite'            => array( 
            'slug'          => 'book', 
            'with_front'    => true,
            'pages'         => true, //pagination 
            'feeds'         => false //rss
        ),
    'supports'           => array( 
                'title',
                'editor',
                'author',
                'thumbnail',
                'excerpt',
               'custom-fields',
                'comments',
                'page-attributes' //IMPORTANT!!!
        )
    );


    register_post_type('books', $args );
}

add_action('init', 'xiong_register_books_post_type' );