Hi,
How to make a hierarchical URL like: domain.com/parent-title/child-title/
for child post type?
I made custom post type "countries" and child custom post type "cities"
And I would like to get URL:
domain.com/germany/berlin
Thanks.
It's not possible with a dynamic URL.
It is possible however with a hardcoded string base as the URL for the child post.
If you head to Toolset > Post Types > edit_your_child_post > Options > Rewrite, you can prepend certain permalink bases (i.e. "/any-string/")
This will then be prepended to the actual post and hence you can do something like this URL:
site.com/custom-hardcoded-part/custom-post-slug
But these are not dynamic means you cannot have the URL like:
site.com/parent-post-type-slug/child-post-type-slug.
This would require custom coding that enhances WordPress itself since this is a limitation of WordPress.
However for example with Taxonomies you may achieve such a result:
domain.com/germany/berlin
Where "Germany" is the Taxonomy, and "Berlin" the Term.
The URL "domain.com/germany/berlin" would then display an archive where you can for example display all posts tagged with "Berlin".
But the posts itself, they would have the URL as dictated by WordPress (usually, site.com/type/post)
Hi Beda,
I already understood that there will not be an easy solution.
I found on the forum the following solution:
https://toolset.com/forums/topic/hierarchical-url-parent-child-custom-post-type/#post-376770
If it is basically working, could you please help me adapt it to my case?
Thanks for the idea with Taxonomies I'll keep it in mind if not be able to do anything with custom post types.
The user there uses this logic:
- the relationship between post types of "Type_One" and "Type_Two" where the URL will be /custom_slug/Type_One-name/Type_Two-name/.
Type_One is the parent type.
Type_Two the child.
Then he puts this in the functions.php:
//URL rewrites rules for nutrition/brand/product
add_action( 'init', function() {
add_rewrite_rule('^ custom_slug/(.*)/([^/]+)/?$','index.php? Type_Two =$matches[2]','top');
});
add_filter('post_type_link', function($link, $post){
if('Type_Two' == get_post_type($post)){
$parentId = wpcf_pr_post_get_belongs($post->ID,'Type_One');
if($parentId){
$parent = get_post($parentId);
return str_replace('Type_Two', $parent->post_name, $link);
}
}
return $link;
}, 10, 2 );
I also see this user is willing to help. He mentions that you may contact him:
hidden link
Note that above API code will change in the future when the stable Many to Many releases are out.
Then, you will need to adapt the code to a new API call.
We can help with this.