WordPress Theme Development single.php

Custom Post Types

Associated Files: functions.php, Custom Post Type UI Plugin, Advanced Custom Fields Plugin

WordPress has 5 core content types. We’ve covered 2 of them, Posts and Pages, which have specifically designed purposes. They ship with WordPress out of the box. You can extend this concept with Custom Post Types “CPT” for more unique purposes. This means you can have content fields to create more unique dynamic content for your website.

For example, you might create a CPT that creates pages for individual portfolio pieces; a product page for your shop or information about your audio and digital services.

Registering Custom Post Types

Registering a new post type in code is relatively straightforward. There are methods and action hooks that you can use to do it.

// adding our own portfolio item
function new_custom_posttype() {

    $args = array();

    // set the CPT Labeks $labels
    
    // set the CPT config arguments

    register_post_type( 'post_type_item', $args ) {
}

add_action( 'init', 'new_custom_posttype' );

What this does is open the door for access to the CPT via the menu in the admin area by telling WordPress to prepare to work with CPTs.

We’ve created a function that does this but we haven’t yet added any configurations. So it doesn’t do anything yet.

The register_post_type() method takes a string ID which is an identifier for the new CPT. It also uses an array of arguments, which we’re passing into a variable called $args.

$args = array();

We can use another variable to organise your CPT’s labels (i.e. the link texts and titles you see in the admin area). For instance, what do you want your CPT to be?

What will be a set of? What will it say on the menu item? You can put all this information and more in its own array of arguments.

<?php ?>

    // an array of string labels, 
    $labels = array(
        'name'               => _x( 'Portfolio items', 'post type general name' ),
        'singular_name'      => _x( 'Portfolio item', 'post type singular name' ),
        'menu_name'          => 'Portfolio CPT'
    );
    
    // an array of CPT arguments
    $args = array();    
?>

You can then pass these labels to the $args array. Here’s an example that sets out what the CPT does and sets its position in the admin area’s main navigation menu.

<?php

    // an array of string labels, 
    
    $labels = array( . . . )
    
    // an array of CPT arguments
    $args = array(
    
        'labels'        => $labels,
        'description'   => 'Holds our custom portfolio items',
        'public'        => true,
        'menu_position' => 5,
        'supports'      => array( 'title', 'editor', 'thumbnail', 'excerpt', 'comments' ),
        'has_archive'   => true,    
    );
    
?>

Link

Registering Post types in plugins

So what we’ve done so far is covered how to create a new Custom Post Type in Code. WordPress has 2 plugins that allow you to create CPTs and easily associate them with their custom fields using easy-to-use GUIs.

Custom Post Type UI Version:            1.16.0 By WebDevStudios
Advanced Custom Fields (ACF) Version:   6.3.1 Author: WP Engine

If you’re following along, go to your plugin repository in the admin area.

Dashboard ----> Plugins ----> Add New plugins

And search for the above plugins. You’ll need to activate them once installed.

Using CPT UI

The Custom Post Types UI (CPT UI) plugin is used to register new post types to your WordPress website, ready for custom fields to be assigned to them.

When registered and created it will add a new Post Type as a URL in the admin area. This is just like WordPress Core Posts; which creates a custom set of blog posts. But they’re not generalised blog Posts.

They’re a set with specific names with as many different custom fields as you want; a set of posts that go beyond just the standard set content editor.

Open the plugin, “CPTUI”.

Dashboard ----> CPTUI ----> Add New Post Type

This is a GUI for creating new post types. The Basic settings require you to enter 3 things to get started.

"Basic Settings"

----> Post Type Slug
----> Plural Label
----> Singular Label

First, type in your identifier for your new Post Type entry. That’s your “Post Type Slug”.

The post type name/slug. Used for various queries for post type content. So you can use this string to refer to an individual CPT in your code and perform actions on them.

Post Type Slug:
    -> new_post_type

The plural label is used for the landing page title for your CPT.

Plural Label
    -> e.g. New Post Type Items

The third and final input; the text you input here is used as the title whenever a singular label is needed.

Singular Label:
    -> e.g. Post Type Item

There’s a second section on this page called “Additional Labels”. This page offers a raft of different inputs and settings; well beyond the scope of this blog. But generally speaking is what they offer is more control over how your CPT will look when you create new instances.

Input a vast range of additional string identifiers – such as for the Viewing an Item, a list of “all items”, or a general description of your CPT or even things to put on the page when there are no existing Posts.

e.g. “Menu Name” … A space for high-level menu name in the dashboard. Post Type Item (CPTUI). If not used, WordPress will put a default one in place.

e.g. “Post Type Description” … A text area box that provides a space to describe what your custom post type is used for.

e.g. “View Item” … Used in the admin bar when viewing editor screen for a published post in the post type.

When you’ve filled in all the labels you want to use, Find the button that says “Add Post Type” and click it.

Advanced Custom Fields and Field Groups

“Advanced Custom Fields” (ACF) is the plugin we use to create custom fields and link them to one or more CPTs. If you’ve activated the plugin go to it via your admin area.

Dashboard ----> ACF ----> Field Groups ----> "+ Add New"

Before anything else, select a string ID that will be the ID for your custom field group.

ACF ----> Add New ----> Add New Field Group (Text Box)

You can see the Post Type you want by looking at its Singular label in the drop down box.

If we go down to the “Settings” panel and location rules we can see the place where we link the Field group we just created, to a CPT.

ACF ------> SETTINGS -----> Location Rules

With the location rules we can set a condition that tells WordPress to display our custom fields when we’re editing an instance of a CPT.

Show this field group if
    -> Post Type ----> is equal ----> Post Type Item

To link the Field Group to a custom post type we need to scroll down the page and find the location rules. And then we can go back and start adding fields. Here’s one example.

The first custom field is ready to start editing from the word go. Start filling in your first custom field.

e.g. Custom Field 1

Field Type - Text
Field Label - "Field One - Text"
Field Name - "field_one"

When you’re ready, publish the field by simply clicking “Save Changes” on the top right corner of the page

ACF ----> Field Groups ----> Save Changes

Go back to the Custom Post Type and try to add a new post.

e.g.
Post Type Item (CPTUI) ----> "Add a new post"

We’ve have now successfully linked a Field Group and all its fields to a Post Type. You will now be able to access the field and be able to add more at later date. It is an entirely different type of post, working in the same way as Posts and Pages, but is a way of adding more unique content.

Custom Fields in Code

When you’ve finished building all your fields in your Field Group, you can choose to export code to add to your functions.php file. Choose a field group to explore PHP code by toggling the checkboxes and clicking “Generate PHP“.

ACF ---> Tools ---> Export ----> Generate PHP

Storing field groups, post types, or taxonomies locally can provide many benefits such as faster load times, the ability to use version control on your changes & dynamic fields/settings.

You can use this to register a local version of the CPT so a plugin is no longer required.

Here’s a simplified example of the kind of code generated. I put it in the functions.php file below any other code.

<?php

add_action( 'acf/include_fields', function() {

    if ( ! function_exists( 'acf_add_local_field_group' ) ) {
		    return;
    }

    acf_add_local_field_group( array(
	      'key' => 'group_6661cac3ec83b',
        'title' => 'Custom Fields (CPTUI)',
	      'fields' => array(
	      
		        array(
		            
		            /* config options */
		        )
	      ),
	      
	      /* more code... */  
    ) );
    
      
} );

?>

Now the code is exported and is a kind of backup of the fields we created, saved to our Theme, rather than on the database. We can use this code to make certain modifications like we did in the GUIs. For example… I added a field instruction to one of the fields by modifying the string value, like this.

'type' => 'text', 'instructions' => 'field instructions added from function files',

To verify that this change is in effect, go to

Dashboard ----> CPTUI ----> Select a post ----> Review your Custom Field(s)

To conclude

Whether you want to work with Custom Post Type plugins, do so with code, or a combination of both, it is up to you and your skill level. Personally, I prefer to use the plugins for ease of use and swiftness of time.

Plugin development is a whole other dimension to WordPress Development, which we may go into further later on in this blog.

Links

ACF Link
Custom Post Types