I had an issue with a custom taxonomy and a custom post type using the same URL.
My URL I am using for my post type is /news and then I have a taxonomy which I need to have /news/cars
I followed this post to get my URL's to work but now I cant access the actual taxonomy listing pages as i get a 404.
Mixing custom post type and taxonomy rewrite structures?
This is my code I am using to do this functionality:
function register_custom_post_types() {
$args = array(
'labels' => array(
'name' => __( 'News' ),
'singular_name' => __( 'News' )
),
'menu_position' => 5,
'public' => true,
'query_var' => 'news',
'has_archive' => 'news',
'hierarchical' => true,
'taxonomies' => array('news_categories'),
'publicly_queryable' => true,
'capability_type' => 'post',
'rewrite' => array('with_front' => false, 'slug' => 'news/%news_categories%'),
'supports' => array('title', 'editor', 'thumbnail', 'revisions', 'page-attributes')
);
register_post_type( 'news', $args);
}
add_action( 'init', 'register_custom_post_types' );
add_action( 'init', 'create_my_taxonomies', 0 );
function create_my_taxonomies() {
register_taxonomy(
'news_categories',
'news',
array(
'labels' => array(
'name' => 'News Categories',
'add_new_item' => 'Add New Category',
'new_item_name' => "New Category"
),
'query_var' => 'news',
'show_ui' => true,
'show_tagcloud' => false,
'hierarchical' => true,
'rewrite' => array(
'with_front' => false,
'slug' => 'news'
)
)
);
}
add_filter('post_type_link', 'news_term_permalink', 10, 4);
function news_term_permalink($post_link, $post, $leavename, $sample) {
if ( false !== strpos( $post_link, '%news_categories%' ) ) {
$glossary_letter = get_the_terms( $post->ID, 'news_categories' );
$post_link = str_replace( '%news_categories%', array_pop( $glossary_letter )->slug, $post_link );
}
return $post_link;
}