What is Custom Post Types in WordPress And How To Register It
Custom Post Types (CPTs) are a powerful feature in WordPress that allow you to manage and organize various types of content beyond the default Posts and Pages. They are particularly useful for structuring data such as Testimonials, Portfolios, Events, and more.
By default, WordPress includes only two primary post types: Posts and Pages. However, if your website requires additional content structures, you can create Custom Post Types by adding specific code to your theme’s functions.php file. Alternatively, you can use a plugin such as Custom Post Type UI, which simplifies the process of creating CPTs without the need for coding.
Implementing CPTs ensures that your content remains well-organized and distinct, making it easier to manage and display.
Practical Example:
Suppose you are developing a real estate website. To efficiently manage property listings separately from blog posts, you would need a custom post type dedicated to properties. Each property listing may require custom fields such as price, location, and size.
How to Register a Custom Post Type
To register a new Custom Post Type, navigate to your theme’s directory: wp-content/themes/your-active-theme/functions.php, and insert the following code before the closing ?> tag.
function register_property_post_type() {
$labels = array(
'name' => _x('Properties', 'post type general name'),
'singular_name' => _x('Property', 'post type singular name'),
'menu_name' => __('Properties'),
'name_admin_bar' => __('Property'),
'add_new' => __('Add New'),
'add_new_item' => __('Add New Property'),
'new_item' => __('New Property'),
'edit_item' => __('Edit Property'),
'view_item' => __('View Property'),
'all_items' => __('All Properties'),
'search_items' => __('Search Properties'),
'not_found' => __('No properties found.'),
'not_found_in_trash' => __('No properties found in Trash.')
);
$args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'rewrite' => array('slug' => 'properties'),
'capability_type' => 'post',
'has_archive' => true,
'hierarchical' => false,
'menu_position' => null,
'supports' => array('title', 'editor', 'thumbnail', 'excerpt', 'custom-fields')
);
register_post_type('properties', $args);
}
add_action('init', 'register_property_post_type');