Site icon WP Smith

Registering Multiple Custom Post Types

Nick Croft has a great post, Custom Post Types Made Easy, on registering multiple custom post types that I have expanded for my purposes.

On almost every install of WordPress I do, I now have at least 2 custom post types: Tweets and Bookmarks.

Since I have this in a plugin, I am using a constant for my URL base:
[php]define( 'WPSPS_URL', WP_CONTENT_URL . '/themes/my-child-theme-folder' );[/php]

First, there is the creation function. This creation function, which I call wps_create_post_types() is the only function that I ever edit, really append.
[php]
add_action( 'init' , 'wps_create_post_types' );
/**
* Create Post Types
*
* @link http://codex.wordpress.org/Function_Reference/register_post_type
*
*/
function wps_create_post_types() {
$post_types = array(
'Tweet' => array(
'rewrite' => array( 'slug' => 'tweets' ),
'menu_icon' => WPSPS_URL . '/lib/images/tweets_16x16.png',
'description' => 'Twitter Archive (@wp_smith)',
'supports' => array( 'title', 'editor', 'custom-fields', 'post-formats' ),
'taxonomies' => array( 'category' , 'post_tag' , ),
),
'Bookmark' => array(
'rewrite' => array( 'slug' => 'tweets' ),
'description' => 'Bookmarks',
'supports' => array( 'title', 'thumbnail', ),
'menu_icon' => WPSPS_URL .'/lib/images/bookmarks16x16.png',
'taxonomies' => array( 'wps_bookmark_category', 'wps_bookmark_tags' ),
),
);
foreach ( $post_types as $title => $args ) {
wps_register_post_type( $title , $args );
}
}
[/php]

So what's going on here is that I am cycling through the post types array registering each post type with a helper function called wps_register_post_type(). Note that I am calling this main function in the init hook, which is required for custom post type registration. So every time I add a new post type I am adding the following:
[php]
'CPT Name' => array(
'post_type' => '', // String
'description' => '', // String
'rewrite' => array( 'slug' => 'cpt-names' ), // Array with 'slug'
'menu_icon' => WPSPS_URL .'/path/to/my/images/bookmarks16x16.png', // String URL
'supports' => array( 'title', 'editor', 'excerpt', 'revisions', 'thumbnail', 'page-attributes', 'custom-fields' ), // Array of strings = features
'taxonomies' => array( 'category', 'post_tag', ),// Array of strings = taxonomies
),
[/php]

First, while I never have to do this (because this is my code and I've set it up how I like it), you can add a post_type entry to your array. This is the name of the registered post type. If you didn't, the helper functions would do it for you. In this case, 'CPT Name' would be registered as wps_cpt_names. It converts the name to lower case and replaces the spaces with underscores. Note, my custom post type name is always my singular title, so if I want to pluralize the slug, then I add a rewrite entry to the array. On all my custom post types I add a menu_icon (call me Vain!), and since custom post types vary, I add my own support entry to the array. However, there does exist a default if you want everything. If I want my custom post type to support some Genesis functionality, I would include them here (e.g., 'genesis-seo', 'genesis-layouts', 'genesis-simple-sidebars').

[php]
/**
* Registers a post type with default values which can be overridden as needed.
*
* @author Nick the Geek
* @author Travis Smith
* @link http://designsbynickthegeek.com/tutorials/custom-post-types-made-easy
* @link http://codex.wordpress.org/Function_Reference/register_post_type
* @link https://wpsmith.net/2012/custom-post-types/registering-multiple-custom-post-types
*
* @uses sanitize_title() WordPress function that formats text for use as a slug
* @uses wp_parse_args() WordPress function that merges two arrays and parses the values to override defaults
* @uses register_post_type() WordPress function for registering a new post type
*
* @param string $title title of the post type. This will be automatically converted for plural and slug use
* @param array $args overrides the defaults
* @param string $prefix prefix string
*/
function wps_register_post_type( $title, $args = array() ) {
$prefix = 'wps_';
$sanitized_title = sanitize_title( $title );
$plural_title = isset( $args['plural_title'] ) ? $args['plural_title'] : '';
unset( $args['plural_title'] );

$defaults = array(
'labels' => wps_post_type_labels( $title , $plural_title ),
'_builtin' => false,
'description' => $title . __( ' Custom Post Type' , 'child-translate-domain' ),
'menu_position' => 6, // WP default: null (below comments ~ 25)
'menu_icon' => '', // WP default: null
'public' => true, // WP default: true
'publicly_queryable' => true, // WP default: value of 'public'
'show_ui' => true, // WP default: value of 'public'
'show_in_nav_menus' => true, // WP default: value of 'public'
'show_in_menu' => true, // WP default: null; 'show_ui' must be true
'has_archive' => true, // WP default: false
'capability_type' => 'post', // WP default: post; defines 'capabilities' as well
'map_meta_cap' => false, // WP default: false
'hierarchical' => false,
'taxonomies' => array(),
'rewrite' => array( 'slug' => $sanitized_title ),
'query_var' => true,
'can_export' => true,
'supports' => array( 'title' , 'editor' , 'excerpt' , 'author' , 'comments' , 'custom-fields' , 'revisions' , 'thumbnail' , 'genesis-seo' , 'genesis-layouts' , 'genesis-simple-sidebars' ),
);

$args = wp_parse_args( $args, $defaults );

// Correct show_in_menu arg
if ( false === $args['show_ui'] && true === $args['show_in_menu'] )
$args['show_in_menu'] = false;

$post_type = isset( $args['post_type'] ) ? $args['post_type'] : $prefix . str_replace( '-', '_', $sanitized_title) . 's';

register_post_type( $post_type, $args );

}
[/php]

While the PHP documentation makes the function self-explanatory, let me explain in a bit more detail. First, I sanitize the title, which formats text for use as a slug. So if the title is: "This Is the Title of My Post," the resulting sanitized title would be: "this-is-the-title-of-my-post." This is important because case and spacing matters.

Then for the arguments, I have a list of default arguments that I use, which basically match the WordPress defaults (and an argument could be made against having them at all). However, I include everything (except capabilities, permalink_epmask, and register_meta_box_cb) so you can see everything that you need or may want.

Next, I am getting my labels from another helper function called wps_post_type_labels()
[php]
/**
* A helper function for generating localizable labels
*
* @author Travis Smith
* @uses _x() WordPress function that retrieves translated string with gettext context
* @uses __() WordPress function that retrieves the translated string from the translate()
*
* @param string $singular Singular Title/Label
* @param string $plural Plural Title/Label (optional)
*/
function wps_post_type_labels( $singular, $plural = '' ) {
if ( $plural == '' ) $plural = $singular . 's';

return array(
'name' => _x( $plural, 'post type general name', 'child-translate-domain' ),
'singular_name' => _x( $singular, 'post type singular name', 'child-translate-domain' ),
'add_new' => __( 'Add New' , 'child-translate-domain' ),
'add_new_item' => __( 'Add New '. $singular , 'child-translate-domain' ),
'edit_item' => __( 'Edit '. $singular , 'child-translate-domain' ),
'new_item' => __( 'New '. $singular , 'child-translate-domain' ),
'view_item' => __( 'View '. $singular , 'child-translate-domain' ),
'search_items' => __( 'Search '. $plural , 'child-translate-domain' ),
'not_found' => __( 'No '. $plural .' found' , 'child-translate-domain' ),
'not_found_in_trash' => __( 'No '. $plural .' found in Trash' , 'child-translate-domain' ),
'parent_item_colon' => ''
);
}
[/php]

This helper labels function pluralizes my labels for me unless I specify a plural label myself, and makes all the strings compatible for localization, which if you are not making your custom post types labels able to be translated, then you need to be. Some of you may say that you never have the need; however, if you get in the practice of localizing, then when you do have the need, your code is already ready/done instead of having to re-invest the work later (which really is more work).

Now, if you want to add Genesis functionality to existing custom post types (that you may have registered via another plugin), then you may need the following.
[php]
add_action( 'init', 'wps_add_post_type_support' );
/**
* Add Genesis custom support for registered post types
* Add Genesis SEO/Layout support to CPTs (if not registered with them)
*
* @uses add_post_type_support() Registers support of certain features for a given post_type
* @link http://codex.wordpress.org/Function_Reference/add_post_type_support
*
*/
function wps_add_post_type_support() {
// Uncomment below as appropriate
//add_post_type_support( 'post_type', 'genesis-seo' );
//add_post_type_support( 'post_type', 'genesis-layouts' );
//add_post_type_support( 'post_type', 'genesis-simple-sidebars' );
}
[/php]

To add the above to multiple post types:
[php]
add_action( 'init', 'wps_add_post_type_support' );
/**
* Add Genesis custom support for registered post types
* Add Genesis SEO/Layout support to CPTs (if not registered with them)
*
* @uses add_post_type_support() Registers support of certain features for a given post_type
* @link http://codex.wordpress.org/Function_Reference/add_post_type_support
*
*/
function wps_add_post_type_support() {
$pts = array( 'post_type1', 'post_type2' );
foreach( $pts as $pt ) {
// Uncomment below as appropriate
//add_post_type_support( $pt, 'genesis-seo' );
//add_post_type_support( $pt, 'genesis-layouts' );
//add_post_type_support( $pt, 'genesis-simple-sidebars' );
}
}
[/php]