Modify a Custom Post Type after it’s been registered
Posted on | 1 minute read
Today I was tasked with adding functionality to an existing custom post type. The problem was, the CPT was being registered in a plugin that I could not edit.
After some digging, I found there’s a filter for that that allows you to modify a custom post type after it’s been registered some other way.
apply_filters( 'register_post_type_args', $args, $post_type );
Hooking into that filter, allowed me to pass additional options to an existing CPT:
/**
* Edit Products CPT arguments.
*
* @see https://developer.wordpress.org/reference/functions/register_post_type/
* @param $args array The original CPT args.
* @param $post_type string The CPT slug.
* @return array The updated CPT.
*/
function grd_edit_cpt( $args, $post_type ) {
// Not the Products CPT? Bail...
if ( 'products' !== $post_type ) {
return $args;
}
// Update CPT arguments.
$updated_args = [
'has_archive' => true,
'supports' => [ 'title', 'editor', 'author', 'thumbnail', 'custom-fields'],
];
// Merge args together.
return array_merge( $args, $updated_args );
}
add_filter( 'register_post_type_args', 'grd_edit_cpt', 10, 2 );
Now “Products” has an archive, along with some other meta boxes in the post editor. Nice!
Comments
No comments yet.
Alvin
Nice post and exactly what i was looking for! I have the same problem: a CPT registered by a plugin doesnt have tags, categories and a text field. I dont want a developer to modify the plugin because its constantly updating. Now i see that this would rather be a “simple” addition to the (child) theme. Thx!
Felipe Romero
Thoroughly explained, thank you very much. This worked wonders for me!
Mohammed
Thanks a lot.. Working so nice!
karl632
Thanks, just what I needed to disable has_archive for a CPT added by the parent theme.
Chet
Thank you!