How to add custom post types in WordPress without plugins
Premise: I hate plugins. 🙂
All you need to create your custom post type (CPT) is to know how register_post_type() function works. Well, around the web there are millions posts about this topic but in the below code you will see a smart function that I’ve realized to registers more than one CPT without repeat the same code again and again.
Let’s say we want to create two CPTs: books and movies. Paste the code in your function.php file and check out the comments for some explainations but what I’m gonna say you is that you can copy&paste the below code, then the only thing you need to do is add an array inside the $types array for each CPT you want.
/*
* Add Custom post types
*/
function netgloo_custom_post_types() {
// Here we go, this is the only thing you need to modify to registers your CPTs:
// write inside this array ($types) an array for each CPT you want
// (and if you need only one CPT simply let one array)
$types = array(
// Books
array('type' => 'book',
'typePlural' => 'books',
'labelSingle' => 'Book',
'labelPlural' => 'Books'
),
// Movies
array('type' => 'movie',
'typePlural' => 'movies',
'labelSingle' => 'Movie',
'labelPlural' => 'Movies'
)
);
// This foreach loops the $types array and creates labels and arguments for each CPTs
foreach ($types as $type) {
$typeSingle = $type['type'];
$typePlural = $type['typePlural'];
$labelSingle = $type['labelSingle'];
$labelPlural = $type['labelPlural'];
// Labels: here you can translate the strings in your language.
// These strings will be displayed in the admin panel
$labels = array(
'name' => _x( $labelPlural, ' post type general name' ),
'singular_name' => _x( $labelSingle, ' post type singular name' ),
'add_new' => _x( 'Aggiungi nuovo ', $labelSingle ),
'add_new_item' => __( 'Aggiungi '. $labelSingle ),
'edit_item' => __( 'Modifica '. $labelSingle ),
'new_item' => __( 'Muovo '. $labelSingle ),
'all_items' => __( 'Tutti le '. $labelPlural ),
'view_item' => __( 'Mostra '. $labelSingle ),
'search_items' => __( 'Cerca '. $labelPlural ),
'not_found' => __( 'Nessun '. $labelSingle .' trovato' ),
'not_found_in_trash' => __( 'Nessun '. $labelSingle .' trovato nel cestino' ),
'parent_item_colon' => '',
'menu_name' => __( $labelPlural ),
);
// Arguments (some settings, to learn more see WordPress docs)
$args = array(
'labels' => $labels,
'description' => 'Holds our products and product specific data',
'public' => true,
'supports' => array( 'title', 'author', 'editor', 'thumbnail', 'excerpt', 'comments', 'page-attributes' ),
'has_archive' => false,
'menu_position' => 5,
'rewrite' => true, // default
'menu_icon' => get_template_directory_uri().'/assets/img/cpt-'.$typeSingle.'.png'
);
// Finally, we can registers the post types
register_post_type( $typeSingle, $args );
} // end foreach
}
add_action( 'init', 'netgloo_custom_post_types' );