Layers Plugin Guide: Adding Custom Post Types & Page Templates

Extension Development

Last Updated: for: 1.5.4 Time to Read: 2 minutes

Custom post types can be registered inside your plugin class, or from within the main plugin file.

The following references register_post_type() and register_taxonomy() and the core WP init hook. Note the extensive use of our constants here where the slug would normally be repeated in single quotes. As a shortcut, we define a pair of variables to cut down on repetition of our post type name. this makes it easier to change, filter and translate.

This example will create a new post type of layers-demo-posts  called Demo Post

Line 3: You must add a condition check for your custom post type name, shown here as layers-demo-posts  , especially if it could potentially already exist. Unique post type names are best, even if using this check, to make absolutely sure the user doesn’t get an error on activation of your plugin.

You can still set your post type slug as something more generic. In this example,  the post type slug is just story  so the permalinks look better. Users can also translate this easily if they are running a multilingual site.

Lines 7-8: We use variables for our post singular and plural name just to make things easier to manage if we need to edit. This also makes it easier for others to translate and filter if needed.

This works just like adding a post type.

Refer to register_taxonomy()

Line 30:  Taxonomies work a little differently than post types in terms of the permalink structure. We use the rewrite argument here to set a more generic, custom slug that can be translated.

Line 33: We use register_taxonomy() to link our new taxonomy called layers-demo-category  to our custom post type created above, layers-demo-posts

This works just like child themes with the exception of the template location. In a plugin, place all your custom template files into the templates sub-folder. (You do not need a partials folder, etc)

In our plugin class __construct()  , we setup this filter:

Now we need to add a new public function to set the correct location of all our template files, which is the templates sub-folder of our plugin.

From there, you only need to ensure all of your custom page templates are in the templates folder, and your custom post type templates follow the recommended template structure and hierarchy.

To set the  single or archive template for your custom post type,
single_template
or
archive_template
can be hooked.  You must use the full internal path, shown here with our dir constant. The subfolder and file should not have a leading slash.

Jump to how to add custom fields to the post editor if you would like to work on meta before getting into widgets or customizer controls.