Update permalinks when new category added to custom post type taxonomy

Have created a collection of Custom Post Types (CPT) for a WordPress theme I am working on (along with their own taxonomies and tags). For the purpose of this question I will just focus on the ‘projects’ CPT.

When a new project category is added, and then linked to in the navigation menu – the user will see a 404 error until permalinks are saved, clearing WordPress’ route caching.

I was thinking the best way to achieve this would be to use flush_rewrite_rules();

Although, saying that – I don’t take it lightly as best practice strongly recommends only using this function when activating/deactivating a plugin. https://codex.wordpress.org/Function_Reference/flush_rewrite_rules#Usage

What I want to do is hook into the action that fires when a new CPT category is created (either via the post or admin screen) and then run the flush rewrite upon that action so that the WP admin doesn’t have to concern themselves with forcing WordPress route caching via update on permalinks.

I looked at this https://wordpress.stackexchange.com/questions/116616/hook-onto-add-new-category for a possible solution and attempted to use this code:

function custom_created_term( $term_id, $tt_id, $taxonomy )
    $project_cpt = 'CPT_PROJECT';  // Edit this to your needs
    $project_tax = 'TAX_PROJECT_CATS';  // Edit this to your needs

    if( DOING_AJAX && $project_tax === $taxonomy )
        // Try to get the post type from the post id in the referred page url
        // Example: /wp-admin/post.php?post=2122&action=edit&message=1

        parse_str( parse_url( wp_get_referer(), PHP_URL_QUERY ) , $params );

        if( isset( $params['post'] ) )
            $post_id = intval( $params['post'] );
            if( $post_id > 0 && $project_cpt === get_post_type( $post_id ) )


But it is not really working out for me. Not sure if I am using the right tool here or if I am doing something wrong. Have searched quite a bit to the solution but I haven’t come up with a good solution to my problem here (can’t find the hook for creating new CPT categories).

Read more here: Update permalinks when new category added to custom post type taxonomy

Leave a Reply

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