How to create custom post type in WordPress?

Creating custom post types in WordPress can be a great way to organize and display different types of content on your site. Whether you want to create a portfolio, team member section, or custom product listings, custom post types can make it easy to manage and display your content in a structured way. Here’s a step-by-step guide on how to create a custom post type in WordPress:

  1. The first step is to create a new PHP file in your theme’s directory. You can name this file anything you like, but it’s a good idea to use a name that reflects the custom post type you’re creating, such as “portfolio.php” or “team-members.php”.
  2. In the new file, you will need to define your custom post type. You can do this by using the register_post_type() function. Here’s an example of how to create a custom post type called “Portfolio”:
Copy codefunction create_portfolio_post_type() {
    register_post_type( 'portfolio',
            'labels' => array(
                'name' => __( 'Portfolio' ),
                'singular_name' => __( 'Portfolio' )
            'public' => true,
            'has_archive' => true,
            'rewrite' => array('slug' => 'portfolio'),
add_action( 'init', 'create_portfolio_post_type' );

Be sure to change the names and arguments to match your custom post type.

  1. Next, you can add custom fields to your custom post type by using the add_meta_box() function. You can use this function to create custom fields for things like images, text, and links. Here’s an example of how to create a custom field for a featured image:
Copy codefunction add_portfolio_meta_box() {
        'portfolio_meta_box', // ID
        'Portfolio Details', // Title
        'show_portfolio_meta_box', // Callback function
        'portfolio', // Screen
        'normal', // Context
        'high' // Priority
add_action( 'add_meta_boxes', 'add_portfolio_meta_box' );
  1. You can now create the callback function that will display the custom field in the admin area. The function should be called show_portfolio_meta_box() in this example.
Copy codefunction show_portfolio_meta_box() {
    global $post;
    $meta = get_post_meta( $post->ID, 'portfolio', true );
    <input type="hidden" name="portfolio_meta_box_nonce" value="<?php echo wp_create_nonce( basename(__FILE__) ); ?>">
        <label for="portfolio[image]">Featured Image</label>
        <input type="text" name="portfolio[image]" id="portfolio[image]" class="regular-text" value="<?php echo $meta['image']; ?>">
  1. Finally, you will need to save the custom field data when the post is saved. You can do this by using the save_post

Leave a Comment

Your email address will not be published. Required fields are marked *