I’m working with a WordPress site where I set up a custom post type called trip along with a custom taxonomy destination-category. I’m running into two main issues.
First, my single post pages are showing 404 errors even though the taxonomy archives work fine. Second, I’m having problems with duplicate slugs getting modified automatically.
<?php
add_action('init', 'register_custom_taxonomy');
function register_custom_taxonomy()
{
register_taxonomy('destination-category', ['trip'], array(
'labels' => array(
'name' => 'location',
'all_items' => 'all locations',
'edit_item' => 'edit location',
'update_item' => 'update location',
'add_new_item' => 'add new location',
),
'public' => true,
'hierarchical' => true,
'rewrite' => array(
'slug' => 'trip',
'with_front' => false,
'hierarchical' => true,
),
'show_admin_column' => true,
'show_in_rest' => false,
));
}
add_filter('post_type_link', 'trip_permalink_structure', 10, 2);
function trip_permalink_structure($link, $post_obj) {
if ($post_obj->post_type !== 'trip') return $link;
$categories = get_the_terms($post_obj->ID, 'destination-category');
if (!empty($categories) && !is_wp_error($categories)) {
return str_replace('%destination-category%', $categories[0]->slug, $link);
} else {
return str_replace('%destination-category%', 'general', $link);
}
}
add_action('init', 'register_trip_post_type');
function register_trip_post_type()
{
register_post_type('trip', array(
'label' => 'Travel Package',
'public' => true,
'rewrite' => array(
'slug' => 'trip/%destination-category%',
'with_front' => false,
'hierarchical' => true
),
'has_archive' => 'trip',
'supports' => array('title', 'editor', 'thumbnail'),
'taxonomies' => array('destination-category'),
'show_ui' => true,
'show_in_menu' => true,
'show_in_admin_bar' => true,
'hierarchical' => true,
'menu_icon' => 'dashicons-location-alt',
'labels' => array(
'name' => 'trip',
'singular_name' => 'trip',
'menu_name' => 'trips',
'add_new_item' => 'add trip',
'edit_item' => 'edit trip',
'new_item' => 'new trip',
'view_item' => 'view',
'search_items' => 'search trips',
'not_found' => 'nothing found',
'not_found_in_trash' => 'trash is empty',
)
));
}
My URLs look like this:
Taxonomy page: site.com/trip/europe/france/paris/
Single post: site.com/trip/europe/france/paris/paris-weekend-package-3days
The taxonomy pages work perfectly, but single posts return 404 errors.
Also, when I create terms with the same slug under different parents (like weekend-special under both paris and london), WordPress automatically changes the second one to weekend-special-london. Same thing happens with post slugs.
How can I fix the 404 issue and handle the duplicate slug problem? Any help would be great.