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.

Source code

The source code developed in this tutorial is available here.