← Tous les articles

How to create a WordPress custom post type and taxonomy without a plugin

Register a custom post type and taxonomy in code with register_post_type() and register_taxonomy(), avoid permalink 404s, make it work in the block editor and query it properly.

How to create a WordPress custom post type and taxonomy without a plugin

Key points

  • Register post types in a small plugin, not the theme, so they survive a theme change.
  • 404s on a new post type almost always come from rewrite rules: flush them once, never on every page load.
  • Enable show_in_rest on both the post type and the taxonomy, or you lose the block editor.

Projects, case studies, job openings, properties, events, team members: as soon as a site has to manage more than posts and pages, it’s tempting to file everything under posts with a dedicated category, or to install a plugin that creates content types in a few clicks. Both work for a while. The first mixes everything into the blog and its RSS feed; the second makes the site depend on a plugin for a dozen lines of code. On our projects, we register post types in code. Here’s how to do it cleanly, along with the mistakes we run into most often when we take over existing sites.

Post type, category or field: picking the right structure

Before writing code, decide on the structure. A new post type makes sense when the items have their own template, their own archive, and don’t belong in the blog’s post list. A category is enough when you’re simply sorting posts. A custom field (post meta) fits a piece of information attached to one item: a price, an event date, a city.

Take an agency showcasing its work. Each project has a detail page, its own list at /projects/, and is grouped by industry sector. That’s the textbook case: a project post type and a sector taxonomy.

Where should the code live? Not in the theme’s functions.php. Switch themes and the projects vanish from the admin, even though they’re still in the database. A small dedicated plugin, or a must-use plugin in wp-content/mu-plugins, keeps content independent from presentation.

Registering the post type with register_post_type()

Registration happens on the init hook. Here’s a complete, commented version covering the options you need in the vast majority of cases:

<?php
/**
 * Plugin Name: Projects (content type)
 */
function wts_register_projects() {
    register_post_type( 'project', [
        'labels'       => [
            'name'          => 'Projects',
            'singular_name' => 'Project',
            'add_new_item'  => 'Add new project',
            'edit_item'     => 'Edit project',
            'all_items'     => 'All projects',
        ],
        'public'       => true,
        'has_archive'  => 'projects',
        'rewrite'      => [ 'slug' => 'projects', 'with_front' => false ],
        'menu_icon'    => 'dashicons-portfolio',
        'show_in_rest' => true, // block editor + REST API
        'supports'     => [ 'title', 'editor', 'thumbnail', 'excerpt', 'revisions' ],
    ] );
}
add_action( 'init', 'wts_register_projects' );
  • The post type key (project) is limited to 20 characters, lowercase, no spaces. Choose carefully: it’s stored in the database for every item, and renaming it later means a migration.
  • has_archive creates the list page. Passing a string sets its URL.
  • with_front => false stops your post permalink prefix (say /blog/) from being added in front of projects.
  • show_in_rest is the option people forget most: without it, the post type opens in the classic editor and isn’t available through the REST API.
  • supports lists editor features. No thumbnail means no featured image; no revisions means no history.

Labels deserve a moment too. Only name and singular_name are required, but without the others the admin shows generic text like “Add New Post” on your projects, which confuses whoever enters the content. On a multilingual site, wrap them in translation functions (__()) with your plugin’s text domain.

Adding a taxonomy with register_taxonomy()

A custom taxonomy is registered the same way, specifying which post types it applies to:

add_action( 'init', function () {
    register_taxonomy( 'sector', [ 'project' ], [
        'labels'            => [ 'name' => 'Sectors', 'singular_name' => 'Sector' ],
        'hierarchical'      => true,   // checkboxes, like categories
        'show_admin_column' => true,   // column in the projects list
        'show_in_rest'      => true,   // required for the block editor
        'rewrite'           => [ 'slug' => 'projects/sector', 'with_front' => false ],
    ] );
} );

The hierarchical flag changes the interface. true shows checkboxes and allows child terms, like categories; false shows a free-text field, like tags. For a classification you want to keep under control (sectors, property types), the hierarchical version prevents duplicates such as “Healthcare” and “healthcare”.

Watch the URL order: if the taxonomy’s prefix starts like the post type’s (projects/sector), make sure no project is called “sector”. When rules clash, WordPress uses the first one that matches, and one of the two pages will return a 404.

The 404 trap: rewrite rules

This is the question we hear most: “I created my post type, it shows up in the admin, but the front end returns a 404.” WordPress maps URLs to queries using a list of rules stored in the database, and registering a new post type doesn’t refresh that list on its own.

The manual fix is to open Settings > Permalinks and click Save, or to run wp rewrite flush. In a plugin, do it on activation:

register_activation_hook( __FILE__, function () {
    // Register the post type, then rebuild the rules once
    wts_register_projects();
    flush_rewrite_rules();
} );

register_deactivation_hook( __FILE__, 'flush_rewrite_rules' );

What not to do, though we still find it regularly: call flush_rewrite_rules() on the init hook. Rebuilding the rules is expensive and rewrites an option in the database; doing it on every page view slows the whole site down. Also remember to flush after any change to rewrite or has_archive, or the old URLs stay live.

Displaying and querying the content

For display, WordPress automatically looks for templates named after the post type. In a classic theme, that’s single-project.php for a single project and archive-project.php for the list. In a block theme, the Site Editor lets you create “Single item: Project” and “Archive: Projects” templates directly, with no PHP file.

To show projects elsewhere, use WP_Query. To change the archive list itself, don’t run a second query inside the template: adjust the main query with pre_get_posts, otherwise pagination will no longer match what’s displayed.

// Show the 3 latest projects in a sector, e.g. on the home page
$projects = new WP_Query( [
    'post_type'      => 'project',
    'posts_per_page' => 3,
    'no_found_rows'  => true, // no pagination: lighter query
    'tax_query'      => [ [
        'taxonomy' => 'sector',
        'field'    => 'slug',
        'terms'    => 'healthcare',
    ] ],
] );
while ( $projects->have_posts() ) {
    $projects->the_post();
    printf( '<a href="%s">%s</a>', esc_url( get_permalink() ), esc_html( get_the_title() ) );
}
wp_reset_postdata();

// Adjust the archive's main query instead of running a new one
add_action( 'pre_get_posts', function ( $q ) {
    if ( ! is_admin() && $q->is_main_query() && $q->is_post_type_archive( 'project' ) ) {
        $q->set( 'posts_per_page', 12 );
    }
} );

Two good habits: no_found_rows when you don’t need pagination, which spares MySQL from counting every match, and wp_reset_postdata() after a secondary loop, or functions like the_title() will print the wrong item afterwards.

FAQ

What happens to my content if I remove the code?

It stays in the database, untouched. It just no longer appears in the admin or on the site. Registering the same post type key again brings it all back.

Do I need a post type or a custom fields plugin?

They work together. The post type defines the “what” (projects); custom fields hold the details specific to each one (client, year, link). You can register the type in code and use a fields plugin, or register meta yourself with register_post_meta().

How do I rename an existing post type?

Update the post_type column of the affected rows in the database (for example with wp db query, after a backup), change the registration, flush the rewrite rules and add redirects if the URLs change.

Need a WordPress site built around your own kinds of content? We develop custom post types, taxonomies and blocks that are easy for your team to fill in.

Partager LinkedIn Facebook X WhatsApp
</>

webtestudio

Agence web : sites WordPress sur mesure, thèmes premium et logiciels SaaS.

Parler de votre projet →