Add support for Custom Post Types
In order to use custom post types in our project we need to add support for our custom post type in frontity.settings.js. We can do this by locating the object for @frontity/wp-source in the packages array and adding the postTypes property to state.source.
The postTypes property takes an array of objects as it's value, with each object in the array defining a distinct post type. We're only defining one post type, namely destinations, so we only add one object to the array.
1
// File: /frontity.settings.js
2
​
3
// ...
4
{
5
"name": "@frontity/wp-source",
6
"state": {
7
"source": {
8
"url": "https://test.frontity.org",
9
"postTypes": [
10
{
11
type: "destinations",
12
endpoint: "destinations",
13
archive: "/destinations"
14
}
15
]
16
}
17
}
18
}
19
// ...
Copied!
The properties of this object are:
Property
Definition
type
the CPT name, defined by the WordPress function register_post_type()
endpoint
this will usually be the same as type unless the args array passed to register_post_type() specifies something different
archive
this is needed if you want to list all the posts of that post type, note that the args array passed to register_post_type() must include 'has_archive' => true for this to work
Frontity now knows about this CPT and will just work with it. Try it! Enter localhost:3000/destinations into your browser's address bar and you should see a listing of our favourite travel destinations. Click on one and it displays using the <Post> component.
And that's it - that's all we need to do to have our project use WordPress CPTs!
However, in the case of this CPT we don't want to display the author and date information so let's tell our <Root> component to use the <Page> component instead for this post type.
If we take a look at the data for one of the CPT URLs we can see that it has a boolean isDestinations property that we can utilise for this purpose.
Frontity in the console
So let's extend our <Switch> component to tell it to use the <Page> component if this value is true.
1
// File: /packages/my-first-theme/src/components/index.js
2
​
3
// ...
4
<Main>
5
<Switch>
6
<List when={data.isArchive} />
7
<Page when={data.isPage} />
8
<Post when={data.isPost} />
9
<Page when={data.isDestinations} />
10
</Switch>
11
</Main>
12
​
13
// ...
Copied!
To finish off let's make this accessible from our menu.
1
// File: /packages/my-first-theme/src/components/index.js
2
​
3
// ...
4
<Menu>
5
<Link link="/">Home</Link>
6
<Link link="/destinations">Destinations</Link>
7
<Link link="/about-us">About Us</Link>
8
</Menu>
9
​
10
// ...
Copied!
Check you're on the right track by comparing your changes with the ones in this commit.
Last modified 5mo ago
Copy link