Blog

How To Automatically Generate Post Type Labels

Free Web Hosting

WordPress’ custom post types are a fantastic way to organise different types of data. It’s quick and easy to spin up a new post type with just a couple of lines of code. Post types can be used to store anything from products, forms, profiles or even logs, pretty much any type of content stored in a repeatable way.

However one of the more time consuming aspects of creating custom post types is setting all the correct labels. There are dozens of labels used for each post type, all used in different contexts. For the best administrative user experience all the labels should be configured, but often they can be overlooked.

To aid with the creation of post type labels, simply drop this function into your functions.php file or custom plugin. From there, you can simply call this function, passing through the singular and plural labels, and the rest will be generated for you. And if needed, individual labels can be overwritten.

<?php
/**
* Generates the post type labels
*
* @param string $single Singular name of the post type.
* @param string $plural Plural name of the post type.
* @param array $overrides Override any generated labels.
* @return array The post type labels
*/
function cameronjonesweb_generate_post_type_labels( $single, $plural, $overrides = [] ) {
$labels = [
'name' => $plural,
'singular_name' => $single,
'add_new' => 'Add New',
'add_new_item' => 'Add New ' . $single,
'edit_item' => 'Edit ' . $single,
'new_item' => 'New ' . $single,
'view_item' => 'View ' . $single,
'view_items' => 'View ' . $plural,
'search_items' => 'Search ' . $plural,
'not_found' => 'No ' . strtolower( $plural ) . ' found.',
'not_found_in_trash' => 'No ' . strtolower( $plural ) . ' found in Trash.',
'parent_item_colon' => 'Parent ' . $single . ':',
'all_items' => 'All ' . $plural,
'archives' => $single . ' Archives',
'attributes' => $single . ' Attributes',
'insert_into_item' => 'Insert into ' . strtolower( $single ),
'uploaded_to_this_item' => 'Uploaded to this ' . strtolower( $single ),
'filter_items_list' => 'Filter ' . strtolower( $plural ) . ' list',
'items_list_navigation' => $plural . ' list navigation',
'items_list' => $plural . 'Posts list',
'item_published' => $single . ' published.',
'item_published_privately' => $single . ' published privately.',
'item_reverted_to_draft' => $single . ' reverted to draft.',
'item_scheduled' => $single . ' scheduled.',
'item_updated' => $single . ' updated.',
];
return wp_parse_args( $overrides, $labels );
}
view raw functions.php hosted with ❤ by GitHub

Did you find this post useful?

YesNo