How To Create custom post type (CPT) in wordpress

Creating a Custom Post Type (CPT) in WordPress allows you to organize content beyond the default post and page types. This is particularly useful for creating specific content structures such as portfolios, testimonials, FAQs, products, or any custom content.

Here’s a step-by-step guide on creating a Custom Post Type in WordPress with code examples.

Step 1: What is a Custom Post Type?

In WordPress, a Custom Post Type is a specific content type that functions like the default “Posts” and “Pages,” but with its own unique characteristics and
functionalities. Custom Post Types enable you to handle different types of content that are distinct from the usual blog posts, such as products, projects, events,
or reviews.

Step 2: Adding the Code to Register a Custom Post Type

To register a Custom Post Type, add the following code to your theme’s functions.php file. If you’re building a custom plugin, you can also include it there.

Example Code to Register a Custom Post Type
Let’s create a Custom Post Type for “Books.”

<?php
// Register Custom Post Type 'Books'
function custom_post_type_books() {
    $labels = array(
        'name'                  => _x( 'Books', 'Post Type General Name', 'textdomain' ),
        'singular_name'         => _x( 'Book', 'Post Type Singular Name', 'textdomain' ),
        'menu_name'             => __( 'Books', 'textdomain' ),
        'name_admin_bar'        => __( 'Book', 'textdomain' ),
        'archives'              => __( 'Book Archives', 'textdomain' ),
        'attributes'            => __( 'Book Attributes', 'textdomain' ),
        'parent_item_colon'     => __( 'Parent Book:', 'textdomain' ),
        'all_items'             => __( 'All Books', 'textdomain' ),
        'add_new_item'          => __( 'Add New Book', 'textdomain' ),
        'add_new'               => __( 'Add New', 'textdomain' ),
        'new_item'              => __( 'New Book', 'textdomain' ),
        'edit_item'             => __( 'Edit Book', 'textdomain' ),
        'update_item'           => __( 'Update Book', 'textdomain' ),
        'view_item'             => __( 'View Book', 'textdomain' ),
        'view_items'            => __( 'View Books', 'textdomain' ),
        'search_items'          => __( 'Search Book', 'textdomain' ),
        'not_found'             => __( 'Not found', 'textdomain' ),
        'not_found_in_trash'    => __( 'Not found in Trash', 'textdomain' ),
        'featured_image'        => __( 'Featured Image', 'textdomain' ),
        'set_featured_image'    => __( 'Set featured image', 'textdomain' ),
        'remove_featured_image' => __( 'Remove featured image', 'textdomain' ),
        'use_featured_image'    => __( 'Use as featured image', 'textdomain' ),
        'insert_into_item'      => __( 'Insert into book', 'textdomain' ),
        'uploaded_to_this_item' => __( 'Uploaded to this book', 'textdomain' ),
        'items_list'            => __( 'Books list', 'textdomain' ),
        'items_list_navigation' => __( 'Books list navigation', 'textdomain' ),
        'filter_items_list'     => __( 'Filter books list', 'textdomain' ),
    );
    $args = array(
        'label'                 => __( 'Book', 'textdomain' ),
        'description'           => __( 'A custom post type for books', 'textdomain' ),
        'labels'                => $labels,
        'supports'              => array( 'title', 'editor', 'thumbnail', 'custom-fields', 'excerpt', 'comments' ),
        'taxonomies'            => array( 'category', 'post_tag' ),
        'hierarchical'          => false,
        'public'                => true,
        'show_ui'               => true,
        'show_in_menu'          => true,
        'menu_position'         => 5,
        'menu_icon'             => 'dashicons-book', // WordPress dashicon for books
        'show_in_admin_bar'     => true,
        'show_in_nav_menus'     => true,
        'can_export'            => true,
        'has_archive'           => true,
        'exclude_from_search'   => false,
        'publicly_queryable'    => true,
        'capability_type'       => 'post',
        'show_in_rest'          => true, // For Gutenberg support
    );
    register_post_type( 'book', $args );
}
add_action( 'init', 'custom_post_type_books', 0 );
?>

 

Code Explanation

1) Labels: These are the names and labels that appear in the WordPress admin interface.
2) Supports: Defines which features the post type will support, like title, editor, featured image, etc.
3) Taxonomies: Connects existing taxonomies (like categories and tags) to the post type.
4) Public: If set to true, the post type will be publicly accessible.
5) Menu Icon: Uses WordPress Dashicons for the admin menu icon. You can replace dashicons-book with other icons.
6) Show in Rest: Enables Gutenberg support for the custom post type.

Step 3: Flushing Rewrite Rules

After registering a new post type, it’s essential to flush the rewrite rules to make the URLs for the custom post type work correctly. This can be done by visiting
the Permalinks settings in the WordPress dashboard and saving the settings.

Alternatively, you can add the following code temporarily:

<?php
add_action( 'after_switch_theme', 'custom_post_type_books' );
?>

This will only run once when you switch themes and automatically flush the rewrite rules.

Step 4: Viewing and Managing the Custom Post Type in WordPress

1) Once registered, you’ll see Books in the WordPress admin menu.
2) You can add, edit, and manage “Books” just like regular posts.

Step 5: Displaying the Custom Post Type on the Frontend

To display “Books” on the frontend, you can create a custom template or use the following code snippets:

Displaying Books in a Template File

You can create a custom page template and add this code to display the “Books” posts:

<?php
add_action( 'after_switch_theme', 'custom_post_type_books' );
?>
This will only run once when you switch themes and automatically flush the rewrite rules.

Step 4: Viewing and Managing the Custom Post Type in WordPress
1) Once registered, you’ll see Books in the WordPress admin menu.
2) You can add, edit, and manage "Books" just like regular posts.


Step 5: Displaying the Custom Post Type on the Frontend
To display "Books" on the frontend, you can create a custom template or use the following code snippets:

Displaying Books in a Template File

You can create a custom page template and add this code to display the "Books" posts:

<?php
$args = array(
    'post_type' => 'book',
    'posts_per_page' => 10,
);
$books = new WP_Query( $args );
if ( $books->have_posts() ) :
    while ( $books->have_posts() ) : $books->the_post();
        ?>
        <h2><?php the_title(); ?></h2>
        <div><?php the_excerpt(); ?></div>
        <?php
    endwhile;
    wp_reset_postdata();
else :
    echo 'No books found';
endif;
?>

This will display a list of books with their titles and excerpts.

Step 6: Adding Custom Taxonomies (Optional)

If you need specific taxonomies for your custom post type, such as “Genres” for books, you can register custom taxonomies like this:.

<?php
function custom_taxonomy_genre() {
    $args = array(
        'label'        => __( 'Genre', 'textdomain' ),
        'rewrite'      => array( 'slug' => 'genre' ),
        'hierarchical' => true,
    );
    register_taxonomy( 'genre', array( 'book' ), $args );
}
add_action( 'init', 'custom_taxonomy_genre', 0 );
?>

Summary:

By creating a custom post type, you can better organize content and tailor WordPress to suit the specific needs of your website. Custom post types are a powerful
feature that unlocks the full flexibility of WordPress as a content management system.

Read Also :-

How to Create a Child Theme in WordPress

how to create copy to clipboard in react native

Leave a Reply