How to create custom post type in WordPress

You are currently viewing How to create custom post type in WordPress

How to create custom post type in WordPress

In WordPress, you can create a custom post type by using the register_post_type function. This function allows you to create a new post type with custom properties and behaviors. Here’s an example of how to use it:

Copy codefunction create_custom_post_type() {
    register_post_type( 'custom_post_type',
        array(
            'labels' => array(
                'name' => __( 'Custom Post Type' ),
                'singular_name' => __( 'Custom Post' )
            ),
            'public' => true,
            'has_archive' => true,
            'supports' => array( 'title', 'editor', 'thumbnail' ),
            'taxonomies'  => array( 'category' )
        )
    );
}
add_action( 'init', 'create_custom_post_type' );

This code creates a new custom post type named “custom_post_type”. You can change the post type name to anything you like. The labels parameter specifies the names that will be used for the post type in the WordPress admin interface. The public parameter set to true, means the post type will be publicly queryable and will show in the front end. The has_archive parameter set to true, means the post type will have an archive page. The supports parameter specifies which features the post type supports, such as the title, editor and thumbnail. The taxonomies parameter specifies which taxonomies the post type should support, in this example it’s category.

You can also use the register_taxonomy_for_object_type function to add custom taxonomies to the custom post type.

Copy coderegister_taxonomy_for_object_type( 'custom_taxonomy', 'custom_post_type' );

You should put the above code in the same function where you register the custom post type, after the register_post_type function.

It’s important to note that you should call these functions only on the ‘init’ action hook, to make sure that the necessary WordPress functionality is available.

Once you have added this code to your theme’s functions.php file or a plugin, you will be able to create and manage custom post type in your WordPress site.

if you need any help in wordpress development click here

Leave a Reply