WordPress Custom Taxonomy With Same Slug As Custom Post Type

If you want the Terms in your Custom Taxonomy to have their URL path containing their Custom Post Type slug instead of Custom Taxonomy slug without showing 404 page, that can be a little tricky, and as I found throughout the blogs and forums quite impossible.

create register post type

// register custom post type
function create_post_types() {
    register_post_type('latestcases', array(
        'labels' => array(
            'name' => 'Latest Cases',
            'all_items' => 'All Latest Cases'
        ),
        'public' => true
    ));
}
add_action('init', 'create_post_types');

// register taxonomy
function create_taxonomies1() {
    register_taxonomy('latestcases_categories', array('latestcases'), array(
        'labels' => array(
            'name' => 'Cases Categories'
        ),
        'show_ui' => true,
        'show_tagcloud' => false,
        'rewrite' => array('slug' => 'latestcases')
    ));
}
add_action('init', 'create_taxonomies1');

And you want to achieve URL structure like this:
http://stackwordpress.com/latestcases

http://stackwordpress.com/latestcases/m1

http://stackwordpress.com/latestcases/m2

 

Rewrite rules
rewrite rule categories slug not for id

so copy and past this code in function file.

/*
 * Replace Taxonomy slug with Post Type slug in url
 * Version: 1.1
 */
function taxonomy_slug_rewrite($wp_rewrite) {
    $rules = array();
    // get all custom taxonomies
    $taxonomies = get_taxonomies(array('_builtin' => false), 'objects');
    // get all custom post types
    $post_types = get_post_types(array('public' => true, '_builtin' => false), 'objects');
    
    foreach ($post_types as $post_type) {
        foreach ($taxonomies as $taxonomy) {
	    
            // go through all post types which this taxonomy is assigned to
            foreach ($taxonomy->object_type as $object_type) {
                
                // check if taxonomy is registered for this custom type
                if ($object_type == $post_type->rewrite['slug']) {
		    
                    // get category objects
                    $terms = get_categories(array('type' => $object_type, 'taxonomy' => $taxonomy->name, 'hide_empty' => 0));
		    
                    // make rules
                    foreach ($terms as $term) {
                        $rules[$object_type . '/' . $term->slug . '/?$'] = 'index.php?' . $term->taxonomy . '=' . $term->slug;
                    }
                }
            }
        }
    }
    // merge with global rules
    $wp_rewrite->rules = $rules + $wp_rewrite->rules;
}
add_filter('generate_rewrite_rules', 'taxonomy_slug_rewrite');

Permalinks

After doing all this, just go to settings/permalinks and save changes using structure /%postname%/, and thats it!
Sp Apply this code i will definetly helpfull this code.

Social Share

Leave a Comment