Modify CPT arguments after it was registered
WordPress

Modify CPT arguments after it was registered

Andrei Surdu Andrei Surdu ยท

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.

Tags:
#CPT #modify #registration

Comments

Share your thoughts and join the conversation

Loading comments...

Leave a Comment

Your email will not be published

Comments are moderated and will appear after approval

0/2000