Using the PostTypes class

sage9

#1

Apologies, but I’m new to the world of composer since moving up to Sage 9. I realise I’m probably missing something fundamental here, but I’m struggling to figure out how to use the PostTypes class.

I have done a composer require jjgrainger/posttypes in the Bedrock directory, so that the class is apparently available, but if I want to create some post types from within the Sage 9 theme (I know - they should be in plugins, but for my needs they fit perfectly well within the theme) where should I create the file and how do I get it picked up by wordpress?

According to the PostTypes docs I have the following in a file called cpt.php

require __DIR__ . '/vendor/autoload.php';

use PostTypes\PostType;

$books = new PostType('book');

$books->register();

Where in the Sage hierarchy should I put it, and do I have create a reference to it somewhere?

Many thanks - this move from Sage 8 to 9 is proving to be a tough one for me!

Edit: Hang on - should I have done composer require jjgrainger/posttypes in the Sage theme directory rather than the Bedrock directory?

So confused :face_with_head_bandage:


#2

Here’s a working example of PostTypes used in a Roots-friendly way as a plugin :


#3

Many thanks for this! Just to be clear, if I fork your example, make my changes and then require my fork with composer then that would pull it in as a regular plugin along with installing automatically when I deploy with Trellis?

I have read the arguments for keeping things like custom post types in plugins, and I understand them - its just that the site I’m building is so specifically tied to it’s theme that all this seems like an overcomplication. How might I use the PostTypes class within my sage theme?

Thanks!


#4

You can use that class however and wherever you want :slight_smile: You installed the package by requiring it in Bedrock’s composer.json file so it’s available to use from anywhere on your WP setup.

So, don’t put them in the theme :smiley:

Nope, not an over-complication. It’s the proper separation.


#5

@MWDelaney Thank you for this example! Can you provide a brief explanation about how to install it?

If I put the plugin.php inside mu-plugins I get wrong path for autoload.


#6

Hi,
This is truly just an example which needs to be heavily revised to work on a real project. The details for the revision are in the README.

As a start, though, you need to include all of the files in the plugin to make it work in either plugins directory.


#7

It works, it works! Thank you for the clarification. I just needed to know that is a plugin itself (all its files included). I’m not a developer and obvious things are not so obvious for me. :wink: