Modify CPT arguments after it was registered

When registering a new custom post type it’s easy to pass the arguments to the register_post_type function directly. It can’t be easier than this. But what happens when you don’t have access to this function? When you want to modify an existing post type that may be defined by another plugin and you are not allowed to edit it?

Short answer: You look for WordPress hooks.

As always, changing something in WordPress can be done with actions and filters. Of course, if they are in the right place. Thankfully we have them here and we can use them. 🙂

Here is how our code looks like:

add_action('register_post_type_args', function ($args, $postType) {
    if ($postType !== 'book'){
        return $args;
    }

    $args['show_in_rest'] = true;
    $args['public'] = true;

    return $args;
}, 99, 2);

register_post_type_args filter is the solution to our problem. It receives the $args used on registration of the new CPT and here we can modify them.

In our example, we are changing the parameters of book CPT by making it public and making it available in REST API. You can modify any parameter that accepts register_post_type function. See the documentation in the WP docs.

Member since January 2, 2019

Fullstack Web Developer with more than 12 years of experience in web development. Adept in all stages of advanced web development. Knowledgeable in the user interface, backend, testing, and debugging processes. Bringing forth expertise in design, installation, testing, and maintenance of web systems. Working exclusively and professionally with WordPress since 2010.

Comments

    Your email address will not be published. Required fields are marked *