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.