Add Custom Post Type to Your Theme Functions File
You may recall in our previous article on custom post types (linked above) how we can create one or many custom post types easily with the Custom Post Type UI plugin. But you don't need a plugin to create custom post types, it just makes the process easier by adding a user interface.
Once you have the code, custom post types can be incorporated into your theme (whether you're using a custom theme or a child theme).In this article, we'll show you how you can custom post types created in the Custom Post Type UI plugin and add them to your theme.
A Few Simple Facts
In order to accomplish the goals in this article, we will cover a few simple facts:
- Why this is important
- Where the code goes
- How to copy code from the CPT UI plugin
- How to copy the code to your
That's all we'll need to do!
Why Is This Important?
In essence, this article will explain how you can take code created by a plugin and incorporate it into your theme so you don't need the plugin. There are many reasons why you might want to do this:
- More control over your code
- Fewer plugins to manage
- Reduced complexity
By incorporating code from a plugin into a theme, you reduce the overall complexity of your site. However, there may always be plugins which are performing many important functions on your site, and you would be best advised to keep those running as they are.
But, in the case of this article, we're working with a plugin that only creates and edits custom post types, which we can easily bring into a theme. Once you've created all the custom post types you require, there's no need to keep the plugin installed on your site.
Where Does the Code Go?
In this article, we're focusing on the theme and assuming you use a
custom theme or a child theme. In that case, we will be using a theme
functions.php. This is a special file WordPress uses to
run custom PHP functions associated with your theme.
First, we will need to access raw PHP code produced by the Custom Post Type UI plugin.
How to Copy Code From Custom Post Type UI
Now we will extract the PHP code for our custom post type from the plugin.
- Log into your WordPress Dashboard
- Click Tools under CPT UI (left panel)
- Choose the Get Code tab at the top
Which code should you copy? If you created multiple custom post types, you will want to copy the code under All CPT UI Post Types. If you only require one custom post type, you will see it listed under its own section.
Copy the Code into the Functions File
Now, you will only need to open your
functions.php file in your
In most cases, it is considered safe to begin a PHP block without closing it:
<?php // The Custom Post Type code pasted here // ...
With the PHP code for your custom post type added to the
functions.php file, make sure to save the file. Also, make
sure to disable the Custom Post Type UI plugin to avoid duplicate
custom post types.