4

Ok, I've seen some similar posts on how to change a custom post type's attributes after it has been registered (in my case, I'm trying to modify a custom post type created by a plugin without modifying the plugin files).

This appears to be working for some properties:

function change_wp_object() {
  $object = get_post_type_object('easy-rooms');
  $object->show_in_menu = true;
}
add_action('init','change_wp_object');

However, I can't seem to get has_archive to change - and it appears to be related to the permalinks. I'm guessing a new rule for /easy-rooms/ isn't being added.

I've tried adding flush_rewrite_rules() (even though it's a bad idea to run it at init) but even that doesn't work. Post type is set to public and if I do change the has_archive in the plugin code it does work.

Any ideas? Thanks in advance!

1
  • I would also like to know this. My post type archives won't change from /?post_type=cpt-something to /somethings/
    – solepixel
    Commented Aug 17, 2016 at 23:40

2 Answers 2

1

If Your WordPress installation is 4.4.0 or highter, you can filter the arguments pass to the register_post_type() function which is eventually pass to the WP_Post_Type::set_props

/**
 * Customize Your Post Type args after post type has been registered.
 * 
 * @param array  $args      Array of arguments for registering a post type.
 * @param string $post_type Post type key.
 * 
 * @return array
 */
function wpse_106784_filter_post_type_args( $args, $post_type ) {
    if ( 'your-custom-post-type' === $post_type ) {
        $args['show_in_menu'] = true;
        $args['has_archive'] = true;
        // any other args you need to cange
    }
    return $args;
}

add_filter( 'register_post_type_args', 'wpse_106784_filter_post_type_args', 10, 2 );

Edit:

Don't forget to update your permalink settings after adding the above snippet to your code. If it's a plugin and your plugin has install method (or activation hook) you can invoke flush_rewrite_rules() function there.

Sources:
https://developer.wordpress.org/reference/functions/register_post_type/#source https://developer.wordpress.org/reference/classes/wp_post_type/set_props/#source

3
  • I'm trying to use this filter to add blog before the slug for the built-in posts, but it seems to do nothing. It works for custom post types, however. Commented Feb 5 at 14:56
  • You should try changing permalink setting from your WordPress dashboard. Commented Feb 15 at 18:20
  • I wanted only posts (but not pages or anything else) to be prepended, so changing permalinks wasn't an option. I ended up solving it by using some custom rewrite rules. Commented Feb 16 at 4:18
0

Be sure 'rewrite' => true is set (to TRUE). Overlooked this converting a CPT without an archive to one with an archive.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.