Chapter 2: Custom Post Types and Taxonomies
Chapter 2 of 15
Chapter 2: Custom Post Types and Taxonomies
2.1 Creating Custom Post Types
Custom post types extend WordPress beyond posts and pages.
// Register custom post type
function register_product_post_type() {
$args = array(
'public' => true,
'label' => 'Products',
'supports' => array('title', 'editor', 'thumbnail'),
'has_archive' => true,
'rewrite' => array('slug' => 'products'),
);
register_post_type('product', $args);
}
add_action('init', 'register_product_post_type');
2.2 Custom Post Type Arguments
Customize post types with extensive arguments.
- public: Make post type publicly accessible
- supports: Enable features (title, editor, thumbnail, etc.)
- has_archive: Enable archive page
- menu_position: Position in admin menu
- menu_icon: Icon for admin menu
2.3 Creating Custom Taxonomies
Taxonomies organize custom post types.
// Register custom taxonomy
function register_product_category() {
$args = array(
'hierarchical' => true,
'label' => 'Product Categories',
'rewrite' => array('slug' => 'product-category'),
);
register_taxonomy('product_category', 'product', $args);
}
add_action('init', 'register_product_category');
2.4 Advanced Taxonomy Features
Use advanced taxonomy features for better organization.
- Hierarchical: Parent-child relationships
- Meta Box: Custom meta box callback
- Capabilities: Control who can manage taxonomies
- Query Var: Enable taxonomy in queries
2.5 Custom Post Type Templates
Create custom templates for post types.
// Template hierarchy for custom post types
single-{post_type}.php
archive-{post_type}.php
taxonomy-{taxonomy}.php