Adding custom post type with support for custom categories in WordPress

CMS
10.08.19

When writing sites on WordPress, sometimes the standard heading functionality is not enough, and there is a need to add a new custom section (or several sections) to the site. Consider adding your own record types with separate templates. Write all the code presented in the functions.php file of your theme.

The whole code looks like this:

function custom_cat() {
    // create a new taxonomy
    register_taxonomy(
        'timeline',
        'timeline-item',
        array(
            'label' => __( 'TL Category' ),
            'rewrite' => array( 'slug' => 'timeline', 'with_front' => false ),
            'capabilities' => array(
                'manage_terms' => 'manage_categories',
                'edit_terms' => 'manage_categories',
                'delete_terms' => 'manage_categories',
                'assign_terms' => 'edit_posts',
            ),
            'show_ui' => true,
            'show_tagcloud' => false,
            'hierarchical' => true
        )
    );
}
add_action( 'init', 'custom_cat' );
 
function create_post_type() {
 
    register_post_type( 'timeline-item',
        array(
            'labels' => array(
                'name' => __( 'Timeline item' ),
                'singular_name' => __( 'Timeline item' ),
            ),
            'rewrite' => array( 'slug' => 'timeline/%timeline%', 'with_front' => false ),
            'public' => true,
            'taxonomies'  => array( 'timeline' ),
            'hierarchical' => true,
            'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments', 'custom-fields' )
        )
    );
    flush_rewrite_rules();
}
add_action( 'init', 'create_post_type' );
 
//fix sef
function wpa_show_permalinks( $post_link, $post ){
    if ( is_object( $post ) && $post->post_type == 'timeline-item' ){
        $terms = wp_get_object_terms( $post->ID, 'timeline' );
        if( $terms ){
            return str_replace( '%timeline%' , $terms[0]->slug , $post_link );
        }
    }
    return $post_link;
}
add_filter( 'post_type_link', 'wpa_show_permalinks', 1, 2 );

Taxonomy templates are created at the root of your theme. In this case, for categories the file will be called taxonomy-timeline.php, and for the entry taxonomy-timeline-item.php.

A new section will appear in the admin menu.

blog comments powered by Disqus