How to Modify a Post Type in WordPress
WordPress has a filter to modify the arguments of a post type during the registration process.
Problem
Sometimes we need to modify a post type, but the registration code is in a file we cannot edit. For example, suppose that a plugin registered the 'ns_testimonial_cpt'
post type without support for archive pages, but we need an archive for this post type.
Solution
Use the 'register_post_type_args'
filter to solve this problem. It allows filtering the arguments of a post type just before it is registered in WordPress.
Functions hooked to this filter receive the current arguments of the post type and the identifier of the post type. They must return the new arguments of the post type.
/**
* Filters the arguments for registering a post type.
*
* @since 4.4.0
*
* @param array $args Array of arguments for registering a post type.
* @param string $post_type Post type key.
*/
$args = apply_filters( 'register_post_type_args', $args, $this->name );
Example
This code modifies the 'ns_testimonial_cpt'
post type mentioned above, so it now supports archive pages.
/*
* Updates the 'ns_testimonial_cpt' post type while it is being registered.
*/
function ns_update_testimonial_cpt($args, $post_type){
if($post_type == 'ns_testimonial_cpt'){
$args['has_archive'] = true;
$args['rewrite'] = array('slug' => 'testimonials');
$args['query_var'] = 'testimonial';
}
return $args;
}
add_filter('register_post_type_args', 'ns_update_testimonial_cpt', 10, 2);
Further reading
I recommend the other tutorials in this series to learn more about post types in WordPress.
- Post Types in WordPress
- How to Register a Custom Post Type in WordPress
- How to Register a Custom Post Type Using a Plugin in WordPress
- How to Unregister a Custom Post Type in WordPress
- How to Modify a Post Type in WordPress
- How to Change the Slug of a Post Type in WordPress
- How to Check if a Post Type Exists in WordPress
- How to Get the Registered Post Types in WordPress
- How to Get the Attributes of a Post Type in WordPress
- How to Get the URL of a Post Type Archive in WordPress
- How to Add Custom Post Types to the Main Query in WordPress
Source code
The source code developed in this tutorial is available here.
Comments