I have a custom post type named landings
which has a rewrite rule to change the slug to loans and a custom taxonomy provinces
and I want the custom post type to have the slug of the province in the permalink.
Basically I want it to be something like this:
/loans --> Custom WordPress Page
/loans/alberta --> Show the taxonomy Alberta (taxonomy-provinces.php)
/loans/alberta/calgary --> Show the landing of Calgary (single-landings.php)
Landings
register_post_type('landings', array(
'label' => 'Landings',
'public' => true,
'rewrite' => array(
'slug' => 'loans/%province%',
'with_front' => false
)
));
Provinces
register_taxonomy('provinces', array('landings'), array(
'label' => 'Provinces',
'hierarchical' => false,
'rewrite' => array(
'slug' => 'loans',
'with_front' => false
)
));
I’ve tried to apply the post_type_link
filter to replace the %province%
in the admin and it works fine for the backend, however when I try to access it via the front I get a 404.
add_filter('post_type_link', function($link, $post = null){
if($post instanceof WP_Post && $post->post_type == 'landings'){
if($province = get_field('province', $post->ID))
return str_replace('%province%', $province->slug, $link);
}
return $link;
}, 1, 2);
So to continue, I’ve updated the rewrite rules of WordPress:
add_action('generate_rewrite_rules', function($wpRewrite){
$rules = array();
$postTypes = get_post_types(array('name' => 'landings', 'public' => true, '_builtin' => false), 'objects');
$taxonomies = get_taxonomies(array('name' => 'provinces', 'public' => true, '_builtin' => false), 'objects');
// Loop through each post type
foreach($postTypes as $postType){
$name = $postType->name;
$slug = $postType->rewrite['slug'];
// Loop through each taxonomy
foreach($taxonomies as $taxonomy){
// Proceed to next taxonomy
if($taxonomy->object_type[0] != $name)
continue;
$terms = get_categories(array('type' => $name, 'taxonomy' => $taxonomy->name, 'hide_empty' => false));
// Loop through each term to create the right rewrite rule
foreach($terms as $term){
$rules[str_replace('%province%', $term->slug, $slug) . '/?$'] = 'index.php?' . $term->taxonomy . '=' . $term->slug;
}
}
}
$wpRewrite->rules = $rules + $wpRewrite->rules;
});
With the rewrite rules above, I managed to get the /loans
and /loans/alberta
working properly. However, when I visit /loans/alberta/calgary
I get a 404 even though in the admin when I edit Calgary, I see the permalink: /loans/alberta/calgary
.
Also, when I scroll down to the Yoast SEO module, I see that the link is /calgary
but when I try to access that permalink, I still get another 404.