Site icon WP Smith

Use registered_post_type Hook to Modify Post Type Registration

If you're anything like me, sometimes a post type doesn't function like you want, or you need to do something slightly different. Many plugins register new custom post types, label them wonky or make them public when you want it to be private, etc. Whatever the case, you do not need the plugin developer to have a filter prior to the registration.

For example:

<?php
add_action( 'init', 'gs_register_books_cpt' );
/**
* Register Books Custom Post Type
*/
function gs_register_books_cpt() {
// change 'gs_books' to whatever your text_domain is.
/** Setup labels */
$labels = array(
'name' => x_( 'Books', 'gs_books' ),
'singular_name' => x_( 'Book', 'gs_books' ),
'add_new' => x_( 'Add New', 'gs_books' ),
'all_items' => x_( 'All Books', 'gs_books' ),
'add_new_item' => x_( 'Add New Book', 'gs_books' ),
'edit_item' => x_( 'Edit Book', 'gs_books' ),
'new_item' => x_( 'New Book', 'gs_books' ),
'view_item' => x_( 'View Book', 'gs_books' ),
'search_items' => x_( 'Search Books', 'gs_books' ),
'not_found' => x_( 'No Books found', 'gs_books' ),
'not_found_in_trash' => x_( 'No Books found in trash', 'gs_books' ),
'parent_item_colon' => x_( 'Parent Book:', 'gs_books' ),
'menu_name' => x_( 'Amazon Books', 'gs_books' )
);
/** Setup args */
$args = array(
'labels' => $labels,
'description' => x_( 'Amazon Books post type', 'gs_books' ),
'public' => true,
'menu_position' => 20,
'supports' => array( 'title', 'editor', 'excerpt', 'page-attributes', ),
'has_archive' => 'books',
'rewrite' => array( 'slug' => 'book', ),
);
/** Register Custom Post Type */
register_post_type( 'gs_books', $args );
}

This creates a menu item labeled Amazon Books, but what if I want that to be just Books?

So if I wanted to change the label, I would do something like this:

<?php
add_action( 'registered_post_type', 'gs_books_label_rename', 10, 2 );
/**
* Modify registered post type menu label
*
* @param string $post_type Registered post type name.
* @param array $args Array of post type parameters.
*/
function gs_books_label_rename( $post_type, $args ) {
if ( 'gs_books' === $post_type ) {
global $wp_post_types;
$args->labels->menu_name = __( 'Books', 'gs_books' );
$wp_post_types[ $post_type ] = $args;
}
}

This is only one method to change custom post types defaults. Alternatively, you can also hook into init at a later time to change them.

<?php
add_action( 'init', 'gs_books_label_rename', 999 );
/**
* Modify registered post type menu label
*
*/
function gs_books_label_rename() {
global $wp_post_types;
$wp_post_types['gs_books']->labels->menu_name = __( 'Books', 'gs_books' );
}