Dynamic URL Rewrite for Custom
I have a custom post type called Hotels
which I woud like to link to using the below url structure:
/{country}/{state}/{hotel-name}
I am fetching and inserting posts dynamically, so I do not know the number of countries/states.
The Hotel Name is the slug version of the post title.
I have been banging my head all day trying to get it to work. The below code works to make the links look correct, but then 404s on all posts:
function change_link($permalink, $post)
{
if ($post-post_type == 'hotels') {
$country = get_field('location_country', $post-ID);
$state = get_field('location_state', $post-ID);
$permalink = get_home_url() . /hotels/
. (!empty($country) ? slugify($country) . '/' : '')
. (!empty($state) ? slugify($state) . '/' : '')
. $post-post_name;
}
return $permalink;
}
add_filter('post_type_link', change_link, 10, 2);
I then tried adding a rewrite rule, but I don't fully understand what it is doing and why it is not working:
function generate_rule($wp_rewrite)
{
add_rewrite_rule(
'/hotels/([^/].+?)/([^/].+?)/([^;?]+)',
'index.php?post_type=hotelsname=$matches[3]country=$matches[1]state=$matches[2]',
'top'
);
}
add_action('init', 'generate_rule');
Woud be much appreciated if someone can point me in the right direction...