Easy way to add Custom Post Type and Custom Fields in Wordpress

Hưng Nguyễn
DevBlogCamp
Published in
6 min readApr 16, 2017

Recently, I’d been working with a Wordpress theme project. The project is to build an internal site for my own business, and through that, I discovered a cool, easy and fast way to add new data types into a Wordpress site.

There is an approach might come up to your mind at the very first moment. That is to add a new table into database, doing some CRUD (create, read, update, delete) codes to make it a resource — thing. Yes, you could do that, but you have to make everything raise from scratch. You have to build an admin page for viewing, creating, updating, validating, some javascripts, css…, and some client site pages all by yourself. Those are a lot of work.

However, Wordpress is a fantastic framework that make your life easier. You can take advantage of many handy Wordpress built-in functions. Sound reasonable huh J.

Ok, let’s begin!

To begin with, I’ll give you a concrete that we are going to build for demonstrating.

Example: We need a system for managing a lot of staffs in our company. With this system, we can create, view, update, delete staff…

1. Custom Post Type

Firstly, we need to create a brand new type call Staff. To accomplish this task, we’ll install Custom Post Type UI plugin. This is a free, powerful plugin for us to create our own custom type in Wordpress.

After that, head into ‘Add/Edit Post Type’ screen by clicking on menu CPT UI on the left sidebar. In this screen, just need to pay attention on some following points:

  • Basic settings section: Post Type Slug is important. You’d better remember this field for its use afterward. For others fields, you can fill them similar to mine or whatever you want. They will show on the menu or somewhere else.
  • Additional labels section: All custom labels for our staff type. This section is optional. You can change the default labels of Wordpress post type by filling your own labels text into the textbox as the instructions below each.
  • Settings section: check like the following figure to skip some unneeded fields:

After that, hitting the button ‘Add Post Type’ to complete all above sections. Ok! lets enjoy our first achievement.

As you can see, there is nothing in the Add New Staff screen, except some default fields that we checked before in the Settings section. That’s why we move on for the next step.

2. Custom Fields

We’d already had the custom type. Now we need to add some custom fields into that type. First, we install plugin ‘Advanced Custom Fields’, then activate it.

Next, click on ‘Custom Fields’ item on the left sidebar, hit on button ‘Add New’ afterwards.

In the ‘Add New Field Group’ screen, click ‘Add Field’, complete some information, so that we can add a new field. Add several fields like below:

And now, the most important thing in this part is to set the rule for Post Type in Location section. Do you remember the staff Post Type Slug that I mentioned before? It’s used for this case. In the Location section, we choose ‘Post Type is equal to staff’ to link the field group to the staff type that we created. Then click ‘Publish’ to complete adding fields.

Now we’re done creating a new custom post type: staff. Coming back to the ‘Add New Staff’ screen, you can see the fields that we have just added. Filling these fields and creating new staff by clicking ‘Publish’.

Here is what the result look like:

3. Custom admin columns

You may wonder why the staff list of above result is not look as good as you expected. It’s true. The staff list screen doesn’t show us any useful information at all. It’s because the list just acts as Wordpress default post list.

So, we get to do some more coding to make the above list useful as it should be.

For you to know, when we use Custom Post Type UI to create our new type (staff), Wordpress automatically generate 2 filter hook call ‘manage_edit-{custome_type_name}_columns’ and ‘manage_{custom_type_name}_posts_custom_column’. For our case, the filter hooks are ‘manage_edit-staff_columns’ and ‘manage_staff_posts_custom_column’. We are going to add these filters to make our custom list view. Lets take a look at the following 2 functions: function faba_staff_column_headers is for make change of columns title, and function faba_staff_column_data is for loading correspondence data.

function faba_staff_column_headers( $columns ) {

// creating custom column header data
$columns = array(
‘cb’=>’<input type=”checkbox” />’,
‘title’=>__(‘Staff Name’),
‘phone_number’=>__(‘Phone Number’),
‘email’=>__(‘Email’),
);

// returning new columns
return $columns;

}

add_filter('manage_edit-staff_columns','faba_staff_column_headers');function faba_staff_column_data( $column, $post_id ) {   // setup our return text   $output = '';   switch( $column ) {      case 'title':         // get the custom name data         $fname = get_field('staff_name', $post_id );         $output .= $fname;         break;      case 'phone_number':         // get the custom email data         $phone_number = get_field('phone_number', $post_id );         $output .= $phone_number;         break;      case 'email':         // get the custom email data         $email = get_field('email', $post_id );         $output .= $email;         break;    }   // echo the output   echo $output;}add_filter('manage_staff_posts_custom_column','faba_staff_column_data',1,2);

Add the above snippet code into functions.php file of our theme. Reload staff list page and see the differences:

Columns title has changed, and also their data. But, wait a second! Do you notice that the ‘Staff Name’ column data? They still show a fixed text: ‘Auto Draft’. It’s because of the new version of Wordpress, but I’m not pretty sure. I just read it somewhere. No worry, it’s not big a deal. We are going to fix it.

Again, we use another filter hook: ‘the_title’ filter. This filter gives us a chance to apply our change to the post title retrieved from the database.

function faba_custom_admin_titles( $title, $post_id ) {   global $post;   $output = $title;   if( isset($post->post_type) ):      switch( $post->post_type ) {         case 'staff':            $fname = get_field('staff_name', $post_id );            $output = $fname;            break;      }   endif;   return $output;}add_filter('the_title', 'faba_custom_admin_titles', 99, 2);

We have completed all of our work. Reload staff list page once again. Congratulation! We did it.

--

--