I generate a tour post type with tour-type taxonomy:
<?php
add_action('init', 'site_register_taxonomy');
function site_register_taxonomy()
{
register_taxonomy('tour-type', ['tour'], array(
'labels' => array(
'name' => 'region',
'all_items' => 'all regions',
'edit_item' => 'edit region',
'update_item' => 'update region',
'add_new_item' => 'add new region',
),
'public' => true,
'hierarchical' => true,
'rewrite' => array(
'slug' => 'tour',
'with_front' => false,
'hierarchical' => true,
),
'show_admin_column' => true,
'show_in_rest' => false,
));
}
add_filter('post_type_link', 'tour_custom_permalink', 10, 2);
function tour_custom_permalink($post_link, $post) {
if ($post->post_type !== 'tour') return $post_link;
$terms = get_the_terms($post->ID, 'tour-type');
if (!empty($terms) && !is_wp_error($terms)) {
return str_replace('%tour-type%', $terms[0]->slug, $post_link);
} else {
return str_replace('%tour-type%', 'uncategorized', $post_link);
}
}
add_action('init', 'create_post_type');
function create_post_type()
{
register_post_type('tour', array(
'label' => 'تور',
'public' => true,
'rewrite' => array(
'slug' => 'tour/%tour-type%',
'with_front' => false,
'hierarchical' => true
),
'has_archive' => 'tour',
'supports' => array('title', 'editor', 'thumbnail'),
'taxonomies' => array('tour-type'),
'show_ui' => true,
'show_in_menu' => true,
'show_in_admin_bar' => true,
'hierarchical' => true,
'menu_icon' => 'dashicons-admin-site-alt',
'labels' => array(
'name' => 'tour',
'singular_name' => 'tour',
'menu_name' => 'tour',
'add_new_item' => 'add tour',
'edit_item' => 'edit tour',
'new_item' => 'new tour',
'view_item' => 'show',
'search_items' => 'search tour',
'not_found' => 'not found',
'not_found_in_trash' => 'not found in trash',
)
));
}
now the result of hierarchical taxonomy is like this:
site.com/tour/turkey/istanbul/istanbul-from-dubai/
for single post is like this:
site.com/tour/turkey/istanbul/istanbul-from-dubai/istanbul-from-dubai-flight-5days
the problem is that I get 404 error for single posts.
another question is how can I shorten my url when I have two similar slug.
for example: I create from-dubai for istanbul parent and another for izmir. when I create number two slug it’s changed to this: from-dubai-izmir. I think that is the behaviour of wordpress for slugs.This behavior is the same when creating single posts. how to change it?
If you have a solution for these two problems, it would be appreciated.