Search by

concept-image / wp-custom-post-types

concept-image

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

Issues

pkg:composer/concept-image/wp-custom-post-types

Statistics

Installs: 2 707

Dependents: 3

Suggesters: 1

Stars: 0

4.2.1 2026-12-02 15:12 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(), a concept-image/wp-query builder 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 with X::archive();
  • resolvers turning classes into names and back (every class is also registered with wp-query's NameResolver);
  • HasFields and HasTag, 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 HasFields and HasTag::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'],
        ];
    }
}
  • $name is the post type key (20 characters max, lowercase, not a reserved WordPress name).
  • getArgs() is static and returns the register_post_type() arguments. It is read when registering and by each label helper, so translated labels follow the current locale.
  • ShouldRegister registers 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_type is read from its default value; the class is never instantiated. It may be empty when post types attach the taxonomy with their taxonomies argument (taxonomies are registered first).
  • $orderBy is 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`
    }
}
  • $query is Builder::query(Book::class) (scopes available). Its vars are set on the main query; the defaults a builder adds to its own queries (post type, publish status, 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, whose public static function archiveQuery(Builder $query): Builder it 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 the int type, else wp-query's per_page config, 12) on the main query, then applies archiveQuery(), whose perPage() wins.
  • With WP_DEBUG on, a class implementing HasArchiveQuery whose archive never runs (a post type without has_archive, a taxonomy that isn't publicly queryable) gets a _doing_it_wrong() notice, once, on wp_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), and public const array ARCHIVE_POST_TYPES = [Book::class]; for the post types it lists (WordPress' choice when empty; with one post type class, $query is built on it). Reuse a post type's declaration (one implementing HasArchiveQuery) with return 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_front front) 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.

ClassYoast SEOCore sitemaps
Post type without archivePost type excludedPost type excluded
Post type with an archiveArchive kept, published posts excluded (at most sitemap.max_excluded_ids)Post type excluded
Post type with public static function getExcludedFromSitemap(): arrayOnly those post IDs excludedOnly those post IDs excluded
TaxonomyExcludedExcluded

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
KeyDefault
paths.post_types, paths.taxonomiesCustomPostTypes, TaxonomiesDirectories, relative to the theme's app/ or absolute
namespaces.post_types, namespaces.taxonomiesApp\CustomPostTypes, App\TaxonomiesTheir namespaces
cacheenv('WP_CUSTOM_POST_TYPES_CACHE'), null: production onlyKeep 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.flushtrueAutomatic rewrite flush
remove_base_slug.enabledtrue#[RemoveBaseSlug]
sitemap.enabled, sitemap.max_excluded_idstrue, 1000ExcludeFromSitemap
editor_panels.hide_without_meta_boxtrueNo block editor panel for taxonomies with 'meta_box_cb' => false
archive_query.enabledtrueApply 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/: the wp-custom-post-types skill (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 (for app/CustomPostTypes and app/Taxonomies) and archives.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.