DEV Community

Cover image for WordPress Custom Post Type Without Plugin: Code Guide
Istiak Ahamed
Istiak Ahamed

Posted on Originally published at kinetix.software

WordPress Custom Post Type Without Plugin: Code Guide

Most tutorials on building a wordpress custom post type without plugin dependencies tell you to paste register_post_type() into your active theme's functions.php file—which guarantees that the moment you switch themes, your portfolio projects, case studies, or research papers vanish from the WordPress admin menu. Even worse, installing a heavy GUI wrapper plugin just to call a single core PHP function adds option-table queries on every request and hides your data schema inside database rows instead of version control. Below is the complete, portable architecture for registering a custom post type, pairing it with a custom taxonomy, exposing it to Gutenberg and the REST API, and wiring its templates cleanly.

Table of Contents


Quick Answer: Register a Portable Custom Post Type in PHP

Create a small standalone functionality plugin at wp-content/plugins/studio-projects/studio-projects.php (or a Must-Use plugin in wp-content/mu-plugins/) and hook register_post_type() into init:

<?php
/**
 * Plugin Name: Studio Projects Content Type
 * Description: Registers the Project custom post type and Project Type taxonomy.
 * Version:     1.0.0
 * License:     GPL-2.0-or-later
 */

defined( 'ABSPATH' ) || exit;

function kx_register_project_post_type(): void {
    register_post_type(
        'kx_project',
        array(
            'labels'       => array(
                'name'          => __( 'Projects', 'kx-projects' ),
                'singular_name' => __( 'Project', 'kx-projects' ),
                'add_new_item'  => __( 'Add New Project', 'kx-projects' ),
                'edit_item'     => __( 'Edit Project', 'kx-projects' ),
            ),
            'public'       => true,
            'has_archive'  => 'projects',
            'rewrite'      => array(
                'slug'       => 'projects',
                'with_front' => false,
            ),
            'show_in_rest' => true,
            'rest_base'    => 'projects',
            'menu_icon'    => 'dashicons-portfolio',
            'supports'     => array( 'title', 'editor', 'thumbnail', 'excerpt', 'revisions', 'custom-fields' ),
        )
    );
}
add_action( 'init', 'kx_register_project_post_type' );

register_activation_hook( __FILE__, function (): void {
    kx_register_project_post_type();
    flush_rewrite_rules();
} );

register_deactivation_hook( __FILE__, 'flush_rewrite_rules' );
Enter fullscreen mode Exit fullscreen mode

Notice two essential lines right away: 'show_in_rest' => true enables the Gutenberg Block Editor and /wp-json/wp/v2/projects, while 'custom-fields' inside 'supports' allows you to bind strongly typed metadata using register_post_meta() and native custom fields.


Where Custom Post Type Code Belongs (Never in functions.php)

When you say "without a plugin," what you really mean is without a third-party GUI post-type builder plugin (like CPT UI, Pods, or JetEngine). You should still place your register_post_type() PHP file inside wp-content/plugins/your-site-core/ or wp-content/mu-plugins/ rather than inside your theme's functions.php.

Here is why separating content architecture from presentation matters:

  1. Data portability across theme switches: If register_post_type( 'kx_project', ... ) lives in your theme, activating a new theme during a redesign immediately unregisters the post type. The rows still sit in wp_posts, but the admin menu disappears, the /projects/* URLs return 404, and nav menu items pointing to projects break.
  2. WordPress.org Theme Review compliance: The official WordPress Theme Review Guidelines explicitly prohibit themes from registering custom post types because doing so locks user content into a single presentation layer (see Gate 1 of our how to submit a theme to WordPress.org review guide). That is the exact reason we split the Kinetix architecture into two parts: the Kinetix Theme handles templates, glass tokens, and layouts, while the free Kinetix Core companion plugin registers the Projects and Research post types.
  3. Activation lifecycle hooks: Standard plugins have register_activation_hook() and register_deactivation_hook(), which give you a clean one-time event to call flush_rewrite_rules().
Storage Location Survives Theme Switch? Supports register_activation_hook? Version-Controlled in Git? Database Option Overhead
Dedicated Functionality Plugin (wp-content/plugins/site-core/) Yes Yes (flushes rewrites once on activate) Yes Zero extra autoloaded rows
Must-Use Plugin (wp-content/mu-plugins/) Yes (always active) No (requires version-flag check if flushing) Yes Zero extra autoloaded rows
Theme functions.php No (content vanishes on theme change) No (after_switch_theme only) Yes Zero, but causes theme lock-in
Third-Party CPT GUI Plugin Yes (as long as GUI plugin stays active) Handled by plugin Only if exported to JSON/PHP manually Stores serialized definitions in wp_options

Lifecycle of a WordPress Custom Post Type Without Plugin Bloat

Understanding when WordPress processes post type definitions prevents two common bugs: registering too early (before translations and $wp_rewrite are ready) or registering too late (after wp_loaded, when rewrite rules and REST controllers have already initialized).

flowchart TD
    A["Request / Plugin Load"] --> B["plugins_loaded (Translations & environment ready)"]
    B --> C["init Priority 10: register_post_type() & register_taxonomy()"]
    C --> D["Populates global $wp_post_types & $wp_taxonomies"]
    D --> E["Adds permastructs to $wp_rewrite in memory"]
    E --> F{"Is this a one-time Plugin Activation?"}
    F -- "Yes (register_activation_hook)" --> G["flush_rewrite_rules() compiles regex & writes to wp_options"]
    F -- "No (Normal Request)" --> H["REST API init: WP_REST_Posts_Controller exposes /wp-json/wp/v2/projects"]
    H --> I["parse_request & WP_Query matches /projects/{slug}"]
    I --> J["Template Loader resolves single-kx_project.html or single-kx_project.php"]

Always hook both register_post_type() and register_taxonomy() to init at priority 10 (or earlier on init, such as priority 5, if other init hooks depend on your post type). Never call register_post_type() outside a hook at the top level of a PHP file, and never delay it until admin_init or wp.


Complete register_post_type() Argument Walkthrough

A production custom post type needs more than 'public' => true. Below is a complete, production-ready kx_project registration class with every key argument documented, followed by a breakdown of what each setting actually controls under the hood.

<?php
/**
 * Complete Project CPT registration with strict labels, capabilities, and REST schema support.
 */

defined( 'ABSPATH' ) || exit;

function kx_register_production_project_cpt(): void {
    $labels = array(
        'name'                  => _x( 'Projects', 'Post type general name', 'kx-core' ),
        'singular_name'         => _x( 'Project', 'Post type singular name', 'kx-core' ),
        'menu_name'             => _x( 'Projects', 'Admin Menu text', 'kx-core' ),
        'name_admin_bar'        => _x( 'Project', 'Add New on Toolbar', 'kx-core' ),
        'add_new'               => __( 'Add New', 'kx-core' ),
        'add_new_item'          => __( 'Add New Project', 'kx-core' ),
        'new_item'              => __( 'New Project', 'kx-core' ),
        'edit_item'             => __( 'Edit Project', 'kx-core' ),
        'view_item'             => __( 'View Project', 'kx-core' ),
        'view_items'            => __( 'View Projects', 'kx-core' ),
        'all_items'             => __( 'All Projects', 'kx-core' ),
        'search_items'          => __( 'Search Projects', 'kx-core' ),
        'not_found'             => __( 'No projects found.', 'kx-core' ),
        'not_found_in_trash'    => __( 'No projects found in Trash.', 'kx-core' ),
        'featured_image'        => _x( 'Project Cover Image', 'Overrides the Featured Image phrase', 'kx-core' ),
        'set_featured_image'    => _x( 'Set project cover image', 'Overrides Set featured image', 'kx-core' ),
        'remove_featured_image' => _x( 'Remove project cover image', 'Overrides Remove featured image', 'kx-core' ),
        'use_featured_image'    => _x( 'Use as project cover image', 'Overrides Use as featured image', 'kx-core' ),
        'archives'              => _x( 'Project archives', 'The post type archive label', 'kx-core' ),
        'item_published'        => __( 'Project published.', 'kx-core' ),
        'item_updated'          => __( 'Project updated.', 'kx-core' ),
    );

    $args = array(
        'labels'              => $labels,
        'description'         => __( 'Studio case studies and client engineering projects.', 'kx-core' ),
        'public'              => true,
        'hierarchical'        => false,
        'exclude_from_search' => false,
        'publicly_queryable'  => true,
        'show_ui'             => true,
        'show_in_menu'        => true,
        'show_in_nav_menus'   => true,
        'show_in_admin_bar'   => true,
        'show_in_rest'        => true,
        'rest_base'           => 'projects',
        'rest_controller_class' => 'WP_REST_Posts_Controller',
        'menu_position'       => 20,
        'menu_icon'           => 'dashicons-portfolio',
        'capability_type'     => 'post',
        'map_meta_cap'        => true,
        'supports'            => array(
            'title',
            'editor',
            'thumbnail',
            'excerpt',
            'custom-fields',
            'revisions',
            'author',
        ),
        'taxonomies'          => array( 'kx_project_category', 'kx_project_tech' ),
        'has_archive'         => 'projects',
        'rewrite'             => array(
            'slug'       => 'projects',
            'with_front' => false,
            'pages'      => true,
            'feeds'      => true,
        ),
        'query_var'           => true,
        'can_export'          => true,
        'delete_with_user'    => false,
    );

    register_post_type( 'kx_project', $args );
}
add_action( 'init', 'kx_register_production_project_cpt', 5 );
Enter fullscreen mode Exit fullscreen mode

Naming Prefix Rules (kx_project vs project)

The first parameter passed to register_post_type() is the post type key stored in the wp_posts.post_type column (varchar(20)). Follow three strict rules:

  1. Maximum 20 characters: WordPress rejects keys longer than 20 characters (_doing_it_wrong).
  2. Lowercase alphanumeric, dashes, or underscores only: No spaces or uppercase letters.
  3. Always prefix the internal key (kx_project), then set 'rewrite' => array( 'slug' => 'projects' ): Using an unprefixed key like project or order risks colliding with plugins or future WordPress core types, whereas prefixing the database key (kx_project) while setting the public URL slug (projects) gives you clean /projects/my-case-study permalinks with zero collision risk.

How Key Arguments Affect Behavior

Argument Default Recommended Value Why It Matters
show_in_rest false true Mandatory for the Block Editor (Gutenberg) and /wp-json/wp/v2/{rest_base}. If left false, WordPress falls back to the legacy Classic Editor screen.
supports ['title', 'editor'] Include 'thumbnail', 'excerpt', 'custom-fields', 'revisions' Omitting 'custom-fields' blocks REST API meta updates and Gutenberg Block Bindings even if you call register_post_meta().
rewrite['with_front'] true false If your blog posts use a prefix like /blog/%postname%, leaving with_front => true forces projects to live at /blog/projects/item instead of /projects/item.
has_archive false 'projects' (or true) Enables the archive listing at /projects and feeds is_post_type_archive( 'kx_project' ).
hierarchical false false (unless you need parent/child pages) Setting hierarchical => true loads every single post of that type into memory to build parent dropdowns in the editor, which degrades badly above a few hundred items.
delete_with_user null false Prevents WordPress from deleting or trashing company portfolio items if an employee's user account is deleted.

Pairing Custom Taxonomies With register_taxonomy()

Avoid attaching core blog category and post_tag taxonomies to a portfolio or research post type unless you truly want your blog categories mixed with project disciplines. Instead, call register_taxonomy() on init to create dedicated taxonomies:

  • Hierarchical taxonomy ('hierarchical' => true): Behaves like categories with checkbox trees (e.g., Project Discipline: Brand Identity, Motion Design, Web Engineering).
  • Non-hierarchical taxonomy ('hierarchical' => false): Behaves like tags with token autocomplete (e.g., Tech Stack: PHP 8.3, WebGL, Three.js, WooCommerce).
<?php
/**
 * Register Project Discipline (hierarchical) and Tech Stack (non-hierarchical) taxonomies.
 */

defined( 'ABSPATH' ) || exit;

function kx_register_project_taxonomies(): void {
    // 1. Hierarchical Taxonomy: Project Disciplines
    register_taxonomy(
        'kx_project_category',
        array( 'kx_project' ),
        array(
            'labels'            => array(
                'name'          => _x( 'Disciplines', 'taxonomy general name', 'kx-core' ),
                'singular_name' => _x( 'Discipline', 'taxonomy singular name', 'kx-core' ),
                'search_items'  => __( 'Search Disciplines', 'kx-core' ),
                'all_items'     => __( 'All Disciplines', 'kx-core' ),
                'edit_item'     => __( 'Edit Discipline', 'kx-core' ),
                'add_new_item'  => __( 'Add New Discipline', 'kx-core' ),
                'menu_name'     => __( 'Disciplines', 'kx-core' ),
            ),
            'public'            => true,
            'hierarchical'      => true,
            'show_ui'           => true,
            'show_admin_column' => true,
            'show_in_nav_menus' => true,
            'show_in_rest'      => true,
            'rest_base'         => 'project-disciplines',
            'rewrite'           => array(
                'slug'         => 'projects/discipline',
                'with_front'   => false,
                'hierarchical' => true,
            ),
        )
    );

    // 2. Non-Hierarchical Taxonomy: Tech Stack
    register_taxonomy(
        'kx_project_tech',
        array( 'kx_project' ),
        array(
            'labels'            => array(
                'name'          => _x( 'Tech Stack', 'taxonomy general name', 'kx-core' ),
                'singular_name' => _x( 'Technology', 'taxonomy singular name', 'kx-core' ),
                'menu_name'     => __( 'Tech Stack', 'kx-core' ),
            ),
            'public'            => true,
            'hierarchical'      => false,
            'show_ui'           => true,
            'show_admin_column' => true,
            'show_in_rest'      => true,
            'rest_base'         => 'project-tech',
            'rewrite'           => array(
                'slug'       => 'projects/tech',
                'with_front' => false,
            ),
        )
    );
}
add_action( 'init', 'kx_register_project_taxonomies', 4 );
Enter fullscreen mode Exit fullscreen mode

Order of Registration Matters When Using Rewrite Slugs

Notice that we hooked kx_register_project_taxonomies at priority 4 and kx_register_production_project_cpt at priority 5, and used 'slug' => 'projects/discipline' for the taxonomy. When a taxonomy permalink shares the /projects/ base prefix with a custom post type, registering the more specific taxonomy permastruct (projects/discipline/([^/]+)) before the broader post type permastruct (projects/([^/]+)) ensures WordPress matches /projects/discipline/motion-design as a taxonomy archive rather than hunting for a project post slug named discipline/motion-design.


Flushing Rewrite Rules on Activation Only

The single most common performance bug in custom post type tutorials is calling flush_rewrite_rules() inside the init callback.

Never do that. Calling flush_rewrite_rules() recalculates every regular expression in $wp_rewrite, runs database UPDATE queries against the rewrite_rules row in wp_options, and invalidates your persistent object cache on every single page view.

Instead, flush rewrite rules only once when your plugin activates or deactivates:

/**
 * Flush rewrite rules strictly on plugin activation and deactivation.
 */
register_activation_hook(
    __FILE__,
    function (): void {
        kx_register_project_taxonomies();
        kx_register_production_project_cpt();
        flush_rewrite_rules( false ); // false = soft flush (updates wp_options without rewriting .htaccess).
    }
);

register_deactivation_hook(
    __FILE__,
    function (): void {
        unregister_post_type( 'kx_project' );
        unregister_taxonomy( 'kx_project_category' );
        unregister_taxonomy( 'kx_project_tech' );
        flush_rewrite_rules( false );
    }
);
Enter fullscreen mode Exit fullscreen mode

Notice why kx_register_project_taxonomies() and kx_register_production_project_cpt() are called explicitly inside the activation closure before flush_rewrite_rules( false ): during activation, ensure your post type's permastructs are registered in $wp_rewrite right before the rules table is compiled and saved.


Template Hierarchy for Classic and Block Themes

Once kx_project is registered, WordPress's template loader automatically searches your active theme for dedicated single, archive, and taxonomy templates. How you build those templates depends on whether your theme is a modern Full Site Editing (FSE) Block Theme (see our complete WordPress custom block theme development guide) or a classic PHP theme.

Route Type Example URL Block Theme Template (templates/) Classic PHP Theme Template Fallback if Not Found
Single Project /projects/obsidian-rebrand templates/single-kx_project.html single-kx_project.php single.html / single.php → singular → index
Project Archive /projects templates/archive-kx_project.html archive-kx_project.php archive.html / archive.php → index
Discipline Archive /projects/discipline/web templates/taxonomy-kx_project_category.html taxonomy-kx_project_category.php taxonomy.html → archive.html → index

In a block theme, templates/archive-kx_project.html uses the core Query Loop block with "inherit": true so WordPress automatically uses the main archive query and pagination:

<!-- wp:template-part {"slug":"header","tagName":"header"} /-->

<!-- wp:group {"tagName":"main","layout":{"type":"constrained"}} -->
<main class="wp-block-group">
    <!-- wp:query-title {"type":"archive"} /-->
    <!-- wp:term-description /-->

    <!-- wp:query {"queryId":1,"query":{"perPage":12,"postType":"kx_project","inherit":true}} -->
    <div class="wp-block-query">
        <!-- wp:post-template {"layout":{"type":"grid","columnCount":3}} -->
            <!-- wp:post-featured-image {"isLink":true,"aspectRatio":"16/10"} /-->
            <!-- wp:post-title {"level":2,"isLink":true} /-->
            <!-- wp:post-excerpt /-->
        <!-- /wp:post-template -->

        <!-- wp:query-pagination {"layout":{"type":"flex","justifyContent":"space-between"}} -->
            <!-- wp:query-pagination-previous /-->
            <!-- wp:query-pagination-numbers /-->
            <!-- wp:query-pagination-next /-->
        <!-- /wp:query-pagination -->
    </div>
    <!-- /wp:query -->
</main>
<!-- /wp:group -->

<!-- wp:template-part {"slug":"footer","tagName":"footer"} /-->
Enter fullscreen mode Exit fullscreen mode

Querying Your Custom Post Type via WP_Query and the REST API

When you need to render a featured projects grid on your homepage or inside a custom block callback, query kx_project with WP_Query. If you are not rendering pagination links on that secondary loop, always pass 'no_found_rows' => true so MySQL skips the extra FOUND_ROWS() count pass:

<?php
/**
 * Render a 6-item featured projects grid filtered by the 'web-engineering' discipline.
 */
$projects_query = new WP_Query(
    array(
        'post_type'      => 'kx_project',
        'post_status'    => 'publish',
        'posts_per_page' => 6,
        'no_found_rows'  => true,
        'tax_query'      => array(
            array(
                'taxonomy' => 'kx_project_category',
                'field'    => 'slug',
                'terms'    => array( 'web-engineering' ),
            ),
        ),
    )
);

if ( $projects_query->have_posts() ) :
    echo '<div class="kx-project-grid">';
    while ( $projects_query->have_posts() ) :
        $projects_query->the_post();
        $client = get_post_meta( get_the_ID(), '_kx_project_client', true );
        ?>
        <article class="kx-project-card">
            <a href="<?php echo esc_url( (string) get_permalink() ); ?>">
                <?php if ( has_post_thumbnail() ) : ?>
                    <?php the_post_thumbnail( 'large', array( 'loading' => 'lazy' ) ); ?>
                <?php endif; ?>
                <h3><?php echo esc_html( get_the_title() ); ?></h3>
            </a>
            <?php if ( is_string( $client ) && '' !== $client ) : ?>
                <p class="kx-project-client"><?php echo esc_html( $client ); ?></p>
            <?php endif; ?>
        </article>
        <?php
    endwhile;
    echo '</div>';
    wp_reset_postdata();
endif;
Enter fullscreen mode Exit fullscreen mode

Fetching Custom Post Types via the REST API

Because we set 'show_in_rest' => true and 'rest_base' => 'projects', WordPress automatically registers standard REST endpoints at /wp-json/wp/v2/projects and /wp-json/wp/v2/project-disciplines. You can fetch published projects with embedded featured images and taxonomy terms in a single request:

curl -s "https://example.com/wp-json/wp/v2/projects?per_page=6&_embed=wp:featuredmedia,wp:term"
Enter fullscreen mode Exit fullscreen mode

And if you want search engines to understand your custom post types—whether they are portfolio projects, software products, or research articles—pair your post type templates with our guide on how to add schema markup to WordPress without a plugin to emit clean CreativeWork, SoftwareApplication, or ScholarlyArticle JSON-LD in wp_head.


Debugging 404 Permalinks and Editor Issues

Troubleshooting: Why do my new custom post type URLs return a 404 page?

  1. Rewrite rules haven't been flushed yet: Visit Settings → Permalinks in the WordPress admin and click Save Changes (without changing any radio buttons). That triggers a one-time flush_rewrite_rules() call.
  2. Slug collision with a static WordPress Page: If you created a standard WordPress Page with the slug projects (/projects) and set 'has_archive' =&gt; 'projects' on your custom post type, the rewrite rules conflict. Delete or rename the static Page (and empty it from the Trash) so the post type archive owns /projects.
  3. publicly_queryable set to false: If you set 'public' =&gt; false and only enabled 'show_ui' =&gt; true, front-end requests to /projects/item-name are blocked unless 'publicly_queryable' =&gt; true is explicitly set.

Troubleshooting: My custom post type opens in the Classic Editor instead of Gutenberg

Gutenberg requires two things in your register_post_type() arguments array:

  1. 'show_in_rest' =&gt; true (so the block editor can load the post payload via /wp-json/wp/v2/...).
  2. 'supports' must include 'editor' (e.g., 'supports' =&gt; array( 'title', 'editor', 'thumbnail' )). If you set 'supports' =&gt; array( 'title' ) without 'editor', WordPress disables the block canvas and renders the classic meta-box screen.

Troubleshooting: Custom taxonomy panel is missing from the Gutenberg sidebar

Even if your custom post type has 'show_in_rest' =&gt; true, any custom taxonomy attached to it must also have 'show_in_rest' =&gt; true inside its own register_taxonomy() arguments array. Without that flag, the taxonomy only appears under the admin submenu and will not render a selector panel inside the Block Editor document sidebar.


Frequently Asked Questions

What happens to my posts if I deactivate the custom post type plugin?

Nothing is deleted from your database. All posts remain safely stored in wp_posts with post_type = 'kx_project', and their metadata stays in wp_postmeta. As soon as you reactivate the plugin (or re-register the same 'kx_project' key), every item and taxonomy term reappears intact.

How do I add custom metadata fields to my custom post type without a plugin?

Add 'custom-fields' to the 'supports' array in register_post_type(), then call register_post_meta( 'kx_project', '_your_meta_key', ... ) on init. We cover the full setup—including REST schema validation and Gutenberg Block Bindings—in our WordPress custom fields without a plugin guide.

Can I include my custom post type in the main blog feed or site search?

Yes. Custom post types with 'public' => true and 'exclude_from_search' => false are already included in front-end search results (/?s=query). To include them on the main blog index or RSS feed alongside standard posts, hook pre_get_posts, check ! is_admin() && $query->is_main_query() && ( $query->is_home() || $query->is_feed() ), and call $query->set( 'post_type', array( 'post', 'kx_project' ) );.

Why does Kinetix ship Projects and Research in Kinetix Core instead of the theme?

Because themes control how a site looks, while plugins control what data a site stores. By registering the Projects and Research post types in the free Kinetix Core plugin rather than the Kinetix Theme, your portfolio items and research publications stay portable even if you switch themes in the future.


Originally published at https://kinetix.software/blog/wordpress-custom-post-type-without-plugin.

Top comments (0)