Skip to content

Registering Post Types

John Blackbourn edited this page Jun 6, 2021 · 6 revisions

The register_extended_post_type() function is the core of Extended CPTs. It's a wrapper for WordPress' own register_post_type() function, which means that any parameters which are accepted by register_post_type() are accepted.

The function's signature looks like this:

function register_extended_post_type( string $post_type, array $args = [], array $names = [] ) : Extended_CPT

Need a simple post type with no frills? You can register a post type with a single parameter:

add_action( 'init', function() {

	register_extended_post_type( 'article' );

} );

Try it. You'll have a hierarchical public post type with an admin UI, and all the labels and post updated messages will be automatically generated.

Tip: Use a singular name for your post type name, such as article instead of articles.

Arguments go into the second parameter, and the third parameter is used to override the singular, plural, and slug arguments which are used as the basis for the post type labels, post updated messages, and permalinks.

add_action( 'init', function() {

	register_extended_post_type( 'story', array(

		# Add the post type to the site's main RSS feed:
		'show_in_feed' => true,

		# Use the block editor:
		'show_in_rest' => true,

		# Show all posts on the post type archive:
		'archive' => array(
			'nopaging' => true
		),

		# Add some custom columns to the admin screen:
		'admin_cols' => array(
			'featured_image' => array(
				'title'          => 'Illustration',
				'featured_image' => 'thumbnail'
			),
			'published' => array(
				'title'       => 'Published',
				'meta_key'    => 'published_date',
				'date_format' => 'd/m/Y'
			),
			'genre' => array(
				'taxonomy' => 'genre'
			)
		),

		# Add a dropdown filter to the admin screen:
		'admin_filters' => array(
			'genre' => array(
				'taxonomy' => 'genre'
			)
		)

	), array(

		# Override the base names used for labels:
		'singular' => 'Story',
		'plural'   => 'Stories',
		'slug'     => 'stories'

	) );

} );

Bam, we have a 'Stories' post type, with correctly generated labels and post updated messages, three custom columns in the admin area (two of which are sortable), stories added to the main RSS feed, and all stories displayed on the post type archive.

Clone this wiki locally