concept-image / wp-custom-post-types
Declare WordPress custom post types and taxonomies as classes in an Acorn theme (app/CustomPostTypes, app/Taxonomies): registration, base slug removal, sitemap exclusion, rewrite flushes, concept-image/wp-query builders and archive queries applied to the main query.
Package info
gitlab.com/concept-image-public/wp-custom-post-types
pkg:composer/concept-image/wp-custom-post-types
Requires
- php: >=8.4
- concept-image/wp-hook-attributes: ^0.1
- concept-image/wp-query: ^1.1
- roots/acorn: ^6.4
Requires (Dev)
- brain/monkey: ^2.6
- larastan/larastan: ^3.0
- laravel/pint: ^1.18
- orchestra/testbench: ^10.0|^11.0
- pestphp/pest: ^4.0|^5.0
- pestphp/pest-plugin-arch: ^4.0|^5.0
- php-stubs/acf-pro-stubs: ^6.5
- szepeviktor/phpstan-wordpress: ^2.0
Suggests
- concept-image/wp-make-cpt: Generates the post type and taxonomy classes (make:cpt, make:tax, presets): ^3.0
Provides
None
Conflicts
None
Replaces
None
- dev-main
- 4.2.1
- 4.2.0
- 4.1.0
- 4.0.0
- 3.1.5
- 3.1.4
- 3.1.3
- 3.1.2
- 3.1.1
- 3.1.0
- 3.0.26
- 3.0.25
- 3.0.24
- 3.0.23
- 3.0.22
- 3.0.21
- 3.0.20
- 3.0.19
- 3.0.18
- 3.0.17
- 3.0.16
- 3.0.15
- 3.0.14
- 3.0.13
- 3.0.12
- 3.0.11
- 3.0.10
- 3.0.9
- 3.0.8
- 3.0.7
- 3.0.6
- 3.0.5
- 3.0.4
- 3.0.3
- 3.0.2
- 3.0.1
- 3.0.0
- 2.0.7
- 2.0.6
- 2.0.5
- 2.0.4
- 2.0.3
- 2.0.2
- 2.0.1
- 2.0.0
- 1.4.4
- 1.4.3
- 1.4.2
- 1.4.1
- 1.4.0
- 1.3.5
- 1.3.4
- 1.3.3
- 1.3.2
- 1.3.1
- 1.3
- 1.2
- 1.1
- 1.0
This package is auto-updated.
Last update: 2026-12-02 14:13:05 UTC
README
Declare WordPress custom post types and taxonomies as classes in an Acorn theme. The package discovers the classes of
app/CustomPostTypes and app/Taxonomies and registers them on init, and adds:
#[RemoveBaseSlug]: post type URLs without the post type slug (/services/audit/→/audit/);ExcludeFromSitemap: keeps a post type or taxonomy out of the Yoast SEO and WordPress core sitemaps;- automatic rewrite flushes when the post types or their slugs change;
- no block editor panel for taxonomies registered with
'meta_box_cb' => false(terms edited through ACF); PostType::query(), aconcept-image/wp-querybuilder with the class'#[Scope]methods;- archive queries declared on the classes (
implements HasArchiveQuery:archiveQuery(),$postsPerPage) and applied to WordPress' main query of post type and term archives, read in templates withX::archive(); - resolvers turning classes into names and back (every class is also registered with wp-query's
NameResolver); HasFieldsandHasTag, traits for the view components of the theme.
Generate the classes with concept-image/wp-make-cpt
(wp acorn make:cpt, wp acorn make:tax, presets).
Requirements
- PHP 8.4+ (
concept-image/wp-query^1.0) - WordPress 6.5+ on Roots Bedrock, Roots Acorn 6.4+
- ACF Pro for
HasFieldsandHasTag::getTagFields()(optional)
Installation
composer require concept-image/wp-custom-post-types
The Acorn service provider is discovered automatically. concept-image/wp-starter-theme already requires the
package.
Post types
One class per file in the theme's app/CustomPostTypes, named after the file:
namespace App\CustomPostTypes;
use ConceptImage\WpCustomPostTypes\Interfaces\ShouldRegister;
use ConceptImage\WpCustomPostTypes\PostType;
final class Book extends PostType implements ShouldRegister
{
protected static string $name = 'book';
protected static int $postsPerPage = 9; // optional: the archive's per page, with HasArchiveQuery (see Archives)
public static function getArgs(): array
{
return [
'labels' => [
'name' => __('Books', 'my-theme'),
'singular_name' => __('Book', 'my-theme'),
],
'public' => true,
'show_in_rest' => true,
'supports' => ['title', 'editor', 'thumbnail'],
'has_archive' => true, // or the archive slug: 'books'
'rewrite' => ['slug' => 'books'],
'taxonomies' => ['genre'],
];
}
}
$nameis the post type key (20 characters max, lowercase, not a reserved WordPress name).getArgs()is static and returns theregister_post_type()arguments. It is read when registering and by each label helper, so translated labels follow the current locale.ShouldRegisterregisters the post type. A class without it only describes an existing post type (post,page, a plugin's) for the label helpers, the resolvers,query()and the sitemap exclusion.- Abstract classes are skipped: a shared parent can live in the directory.
Static helpers: Book::name(), getArgs(), pluralLabel() (name), singularLabel(), allLabel(),
emptyLabel() (not_found), viewLabel(), label('key'), hasArchive() (true for true or a slug),
getArchiveLink(), isSingle() / isNotSingle(), isArchive() / isNotArchive(), postsPerPage() (the class'
protected static int $postsPerPage, else the wp-query.per_page config; see Archives), archive(), and
query():
$books = Book::query()->perPage(3)->get(); // wp-query Builder on the published books
$picks = Book::query()->featured()->take(3); // a #[Scope] public static method of Book
Taxonomies
One class per file in app/Taxonomies:
namespace App\Taxonomies;
use App\CustomPostTypes\Book;
use ConceptImage\WpCustomPostTypes\Interfaces\ShouldRegister;
use ConceptImage\WpCustomPostTypes\Taxonomy;
final class Genre extends Taxonomy implements ShouldRegister
{
public static $orderBy = 'name'; // optional: term order in wp-query filters (default 'slug')
protected static string $name = 'genre';
public array $object_type = [Book::class]; // post type names or classes, may be empty
public static function getArgs(): array
{
return [
'labels' => ['name' => __('Genres', 'my-theme')],
'public' => true,
'hierarchical' => true,
];
}
}
$object_typeis read from its default value; the class is never instantiated. It may be empty when post types attach the taxonomy with theirtaxonomiesargument (taxonomies are registered first).$orderByis a term property ('slug','name'…) or['field' => 'acf_field']/['field_num' => 'acf_field']. Keep it untyped.
Terms edited through ACF: 'meta_box_cb' => false
When an ACF taxonomy field edits the terms (make:tax inserts one), set 'meta_box_cb' => false in getArgs(). It
only removes the classic meta box: the block editor shows a taxonomy panel when the /wp/v2/taxonomies REST response
says visibility.show_ui. The package sets it to false (rest_prepare_taxonomy) for every taxonomy whose
meta_box_cb is false, the package's or not. visibility only exists in the edit context the editor requests;
wp-admin menus, term screens, quick edit and admin columns read show_ui from the PHP taxonomy object, which is
unchanged. Turn it off with editor_panels.hide_without_meta_box.
Archives
The main query of a post type archive or a term archive is declared on the class, which implements
ConceptImage\WpCustomPostTypes\Interfaces\HasArchiveQuery, and applied with $query->set() in
pre_get_posts (front end, main query, not a feed nor a search). WordPress still runs one query: the template, the
404 (out-of-range pages included), the canonical redirect, Polylang, SEO plugins and pagination are native.
use ConceptImage\WpCustomPostTypes\Interfaces\HasArchiveQuery;
use ConceptImage\WpQuery\PostQuery\Builder;
use ConceptImage\WpQuery\Support\TaxonomyFilter;
final class Book extends PostType implements HasArchiveQuery, ShouldRegister
{
protected static int $postsPerPage = 9;
public static function archiveQuery(Builder $query): Builder
{
return $query
->filters([TaxonomyFilter::make(Genre::class)->archive()]) // read from the request
->withThumbnail()->withTerms('genre'); // eager loading, on `the_posts`
}
}
$queryisBuilder::query(Book::class)(scopes available). Its vars are set on the main query; the defaults a builder adds to its own queries (post type,publishstatus, per page, page) are not: they are the request's.- Opt-in per class: the archive query applies only when the class (or a theme parent class) implements
HasArchiveQuery, whosepublic static function archiveQuery(Builder $query): Builderit must declare (the base classes have no default). Other archives stay WordPress' own (Settings > Reading posts per page), even when their class redeclares$postsPerPage. - Per page: the hook sets
Book::postsPerPage()(the class'protected static int $postsPerPage, keep theinttype, else wp-query'sper_pageconfig, 12) on the main query, then appliesarchiveQuery(), whoseperPage()wins. - With
WP_DEBUGon, a class implementingHasArchiveQuerywhose archive never runs (a post type withouthas_archive, a taxonomy that isn't publicly queryable) gets a_doing_it_wrong()notice, once, onwp_loaded. - The eager loading declared with
with…()runs once on the main query's posts (the_posts). - Taxonomy classes declare their term archive the same way (
implements HasArchiveQuery,$postsPerPage), andpublic const array ARCHIVE_POST_TYPES = [Book::class];for the post types it lists (WordPress' choice when empty; with one post type class,$queryis built on it). Reuse a post type's declaration (one implementingHasArchiveQuery) withreturn Book::archiveQuery($query);(add->perPage(Book::postsPerPage())for its per page too).
The template's View Composer (wp acorn make:composer BookArchive) reads the main query, never runs its own, and
passes it to the view, which only loops and displays (no @php, query or get_field() in Blade views):
namespace App\View\Composers;
use App\CustomPostTypes\Book;
use Roots\Acorn\View\Composer;
final class BookArchive extends Composer
{
protected static $views = ['archive-book', 'taxonomy-genre'];
public function with(): array
{
return ['books' => Book::archive()];
}
}
{{-- resources/views/archive-book.blade.php --}}
@foreach ($books as $book) <x-book-card :item="$book" /> @endforeach
{!! $books->getPagination() !!}
What a card shows per item (its genre, an ACF field of the term, a related post) is computed in its component class
(BookCard, HasTag / HasFields below) from the data archiveQuery() eager-loads (withTerms(), withAcf()):
no query per card. Views generated by wp-make-cpt 3.2 still read X::archive() in the view; prefer a composer.
archive() wraps global $wp_query in a wp-query PaginatedResults. Turn the whole feature off with
archive_query.enabled.
Removing the base slug
use ConceptImage\WpCustomPostTypes\Attributes\RemoveBaseSlug;
#[RemoveBaseSlug]
final class Book extends PostType implements ShouldRegister { /* … */ }
/books/dune/ becomes /dune/:
- the permalink loses the rewrite slug (with the
with_frontfront) right after the home URL, or after one language segment (Polylang); - a request for
/dune/is served from the post type when no page or post has that path (pages and posts win), with its extra query vars (lang,page,cpage,embed) kept; - only registered, publicly queryable post types with rewrites qualify, and nothing changes in wp-admin.
Sitemaps
Implement ExcludeFromSitemap on a post type or a taxonomy. It works with Yoast SEO and the WordPress core
sitemaps, and keeps what other code already excluded.
| Class | Yoast SEO | Core sitemaps |
|---|---|---|
| Post type without archive | Post type excluded | Post type excluded |
| Post type with an archive | Archive kept, published posts excluded (at most sitemap.max_excluded_ids) | Post type excluded |
Post type with public static function getExcludedFromSitemap(): array | Only those post IDs excluded | Only those post IDs excluded |
| Taxonomy | Excluded | Excluded |
Rewrite rules
The rewrite rules are flushed once, late on init, when the registered post types or taxonomies change (names,
rewrite slugs, has_archive, hierarchical, query_var, #[RemoveBaseSlug]). The signature is stored per locale
in the wp_custom_post_types_rewrite option. Adding a post type no longer needs a permalink save. Turn it off with
rewrite.flush and run wp rewrite flush yourself.
View components
use ConceptImage\WpCustomPostTypes\Traits\HasFields;
use ConceptImage\WpCustomPostTypes\Traits\HasTag;
use Illuminate\Contracts\View\View;
final class BookCard extends Component
{
use HasFields, HasTag;
protected array $fields = ['sub_title', 'release_date']; // getFields(): ['subTitle' => …, 'releaseDate' => …]
protected array $optionFields = ['archive_title']; // getOptionFields()
protected array $termFields = ['color']; // getTermFields($term)
protected string $fieldPrefix = 'book_'; // optional
protected string $tagTaxonomy = 'genre'; // HasTag's default taxonomy
public function __construct(private WP_Post $item) {}
public function render(): View
{
return view('components.book-card', [
...$this->getFields(), // $subTitle, $releaseDate
'genre' => $this->getTag(), // first term, primed by withTerms('genre')
'genreLink' => $this->getTagLink(),
]);
}
}
The trait methods are protected: call them in render() and pass ready variables, the view only displays them.
HasFields:getField($selector, $id = null),getFields(),getOptionFields(),getTermFields($term). Values are null when ACF is not active.HasTag:getTag(),getTagSlug(),getTagLink(),getTags(),getTagNames($taxonomy, ', '),getTagFields($taxonomy, ...$fields). Each returns null when the post has no term.Helpers\TaxonomyHelper::getParent(WP_Term $term): the parent term, or null.
Resolvers
Support\PostTypeResolver and Support\TaxonomyResolver turn a class or a name into a WordPress name, and back:
PostTypeResolver::resolve(Book::class); // 'book'
PostTypeResolver::resolve('post'); // 'post' (built-in and unknown names are returned as is)
PostTypeResolver::resolveClass('book'); // Book::class, null when no class describes it
PostTypeResolver::resolveId($post); // int|null, null for null
PostTypeResolver::resolvePost(12); // WP_Post|null
TaxonomyResolver::resolve(Genre::class); // 'genre'
TaxonomyResolver::resolveClass('genre'); // Genre::class
Configuration
The defaults need no configuration. To change one, publish config/custom-post-types.php into the theme:
wp acorn vendor:publish --tag=wp-custom-post-types-config
| Key | Default | |
|---|---|---|
paths.post_types, paths.taxonomies | CustomPostTypes, Taxonomies | Directories, relative to the theme's app/ or absolute |
namespaces.post_types, namespaces.taxonomies | App\CustomPostTypes, App\Taxonomies | Their namespaces |
cache | env('WP_CUSTOM_POST_TYPES_CACHE'), null: production only | Keep the discovered class list in Acorn's cache, keyed by the package version and the directory's modification time. Arguments and labels are never cached |
rewrite.flush | true | Automatic rewrite flush |
remove_base_slug.enabled | true | #[RemoveBaseSlug] |
sitemap.enabled, sitemap.max_excluded_ids | true, 1000 | ExcludeFromSitemap |
editor_panels.hide_without_meta_box | true | No block editor panel for taxonomies with 'meta_box_cb' => false |
archive_query.enabled | true | Apply archiveQuery() and postsPerPage() to the main query of the post type and term archives whose class implements HasArchiveQuery (and the WP_DEBUG notice) |
ConceptImage\WpCustomPostTypes\Registry\Registry::clearCache() forgets the discovered classes (wp-make-cpt calls
it after generating one).
Claude Code
Bedrock projects have no Laravel Boost, so the package publishes its AI guidance into the Bedrock root, where Claude Code loads it:
.claude/skills/wp-custom-post-types/: thewp-custom-post-typesskill (declaring post types and taxonomies, archives,#[RemoveBaseSlug], sitemaps, rewrite flushes, traits, resolvers, config, pitfalls);.claude/rules/wp-custom-post-types/:wp-custom-post-types.md(always loaded),post-types.md(forapp/CustomPostTypesandapp/Taxonomies) andarchives.md(archive templates, composers and components).
wp acorn starter:ai (wp-starter-theme) publishes them with the other packages'. Alone:
wp acorn vendor:publish --tag=wp-custom-post-types-ai --force # skill and rules
wp acorn vendor:publish --tag=wp-custom-post-types-skill --force # skill only (wp-custom-post-types-rules: rules only)
Upgrading
From 3.x or 4.1, see UPGRADE.
Testing
composer ci # Pint, Larastan (level max), Pest
Without PHP's dom/xml/mbstring extensions on the host:
docker run --rm -u "$(id -u):$(id -g)" -v "$PWD":/app -w /app composer:2 composer ci.
Changelog
Please refer to CHANGELOG for more information.
Contributing
Please refer to CONTRIBUTING for more information.
License
Please refer to LICENSE for more information.