Custom Post Types in WordPress

Custom Post Types in WordPress
COMMENTS ()
Tweet

Hey Guys,

In my last post I showed you how you to create your first WordPress plugin. In this post we’re going to look at Custom Post Types (CPT) are and how you can create one yourself.

As you know, WordPress comes provides a few standard post types. Among those post and page are notable. Yes, post itself is a post type that is typically used for blogs. WordPress provides an easy-to-use interface to manage posts for default post types. These posts are stored in the wp_posts table which contains a column called post_type that defines what the record’s post type is.


Why Do You Need Custom Post Types?

Simply put, you need Custom Post Types when you want to display something more than what the standard WordPress post types offer. For example, if you want to display books along with their details in a different section of your website. Of course you can place all those details in the description of a post but that’s not going to work when you need to sort or search books based on details like their ISBN or category. It’ll be very hard to manage without using a Custom Post Type. A better way to go about it would be to create a Custom Post Type for books, as that will provide you flexibility. Then you can store any desired set of data in your Custom Post Type and display it exactly the way you want.


Registering your Custom Post Types

Let’s start our tutorial by creating a plugin (please look at my old post if you don’t know how to create one) in which we’ll place all our code for managing our Custom Post Type. After adding a plugin, we’ll need to register our Custom Post Type ‘book’ in WordPress. For that we’ll use the function below:

register_post_type.

This function takes two parameters:

$post_type: (string) (required) – which is the name of your desired post type (max. 20 characters. Cannot contain capital letters or spaces)
$args: (array) (optional) – this is an array of arguments that define the configuration of your Custom Post Type.

To use this function, we’ll have to hook it into the ‘init’ phase. To do so, place the following code snippet in the plugin php file that you just created.


array(
'name' => __('Books'), // General name for the post type
'singular_name' => __('Book')
),
'public' => true, // Controls visibility for readers
'exclude_from_search' => true, // Restricts posts from this post type getting included in the frontend search results
'has_archive' => true, // Enables archiving
'menu_position' => 15, // Menu position in the sidebar
'show_ui' => true, // To use WordPress' default Edit page or not
'rewrite' => array(
'slug' => 'book', // Permalink structure slug. Default: $post_type
'with_front' => false // Whether the permalink structure be perpended with the front base or not
),
'supports' => array( // Fields to show in edit/create page
'title',
'editor',
'custom-fields',
'thumbnail',
),

);

register_post_type('book', $args);
}

add_action('init', 'register_book_post_type');

?>

And that’s it! You just registered your first Custom Post Type in WordPress. Now if you go to the WordPress admin, you’ll see a tab for your Custom Post Type(s) just below the Posts tab in the admin sidebar. You might be wondering why this Custom Post Type looks exactly like the ‘Posts’ section and why you can’t see its custom fields. Well, that’s because in our configuration code (above), we set ‘show_ui’ to true, due to which WordPress presented us with the default UI for this Custom Post Type and since we haven’t added any custom fields to it yet, you can’t see any custom fields for it.

There are more options that you can configure for Custom Post Types. To learn more about that, please visit WordPress Codex.

You can also customize this edit/create page in two ways. You can either add meta box fields to the current page or setup a new edit page from scratch. We’ll be using the first approach in this guide.

Adding Meta box fields to Edit Page

With the help of WordPress Hooks, we can add our custom fields in a Meta box using the function add_meta_box. The code below will help you understand how you can use this function.


ID, 'book_isbn', true));
$book_rating = intval(get_post_meta($book->ID, 'book_rating', true));
?>

Book ISBN
Book Rating


Basically what we’ve done in the code snippet above is that we’ve added our Meta box and printed our custom input fields using the callback function display_book_meta_box. This callback function receives the current post object, which is then used to retrieve and display stored custom fields data (for the current post).


Saving Custom Fields data to the Database

You’ll notice that the meta box with custom fields now appears in the edit page, but it’s values don’t show after saving changes. That’s because we haven’t told WordPress what to do with those fields. We can store this data in the wp_postmeta table, which contains the metadata for posts. The data stored in this table in a key-value pair. The functions add_post_meta and update_post_meta are used to add and update post metadata. Look at the code below for details on how to save data from your meta box.


post_type == 'book'){
// Store custom field values as post meta
$book_isbn = (isset($_POST['book_isbn']) && !empty($_POST['book_isbn'])) ? $_POST['book_isbn'] : '';
$book_rating = (isset($_POST['book_rating']) && !empty($_POST['book_rating'])) ? $_POST['book_rating'] : '';
update_post_meta($book_id, 'book_isbn', $book_isbn);
update_post_meta($book_id, 'book_rating', $book_rating);
}
}

add_action('save_post', 'save_book_custom_fields', 10, 2);

?>


Theme structure for your Custom Post Types

We’re almost done with our Custom Post Type. Now all that’s left to do is add Custom Post Type Templates. You can choose any you want but you have to follow the WordPress naming convention for file names. For single posts, your template file name should be single-{post_type}.php, and for archives it should be of the format archive-{post_type}.php. These two files go into your custom theme’s main directory. If WordPress doesn’t find these files in your active theme directory, it uses single.php and archive.php to display your Custom Post Type. You’ll have to use the function get_post_meta in your template file to retrieve your custom field data while you’re in the Loop using the post ID, like we did with the display_book_meta_box function. I won’t be covering the theme template in this blog post, since that’s a topic for a separate post.


Wrapping up

Hopefully by now you’ll have learnt how to customize your WordPress application to manage and display different types of content. Custom Post Types are extremely powerful tool for this purpose. I would recommend you read up on and play around with Custom Post Types a bit more so you’re well versed with them.

ABOUT FOLIO3

As a leading mobile app development company (iPhone, Android, Windows Phone, HTML5 app development), Folio3 specializes in native app development services and cross platform mobile app development services for the iPhone and iPad. We also offer extensive mobile app testing and QA services. If you have a mobile app idea that you’d like to discuss please or would like to know more about our iPhone app development services, please Contact Us. Learn more about our iPhone, Android and Windows Phone app development services.

CALL

USA408 365 4638

VISIT

1301 Shoreway Road, Suite 160,

Belmont, CA 94002

Contact us

Whether you are a large enterprise looking to augment your teams with experts resources or an SME looking to scale your business or a startup looking to build something.
We are your digital growth partner.

Tel: +1 408 365 4638
Support: +1 (408) 512 1812