[WordPress] How to set permalinks with multiple categories in a hierarchy
![[WordPress] How to set permalinks with multiple categories in a hierarchy](img/ogp.png)
What I want to do
For example,
- Tokyo Branch (tokyo)
- Kansai Branch (kansai)
- Blog (blog)
- News (news)
with these four categories:

When two categories, "Tokyo Branch" and "Blog", are set for a post,

If nothing is done, the permalink will be one of the following:
/tokyo/hello_tokyo/
/blog/hello_tokyo/
The goal is to make it a directory hierarchy like this. (Like "Tokyo Branch Blog")
/tokyo/blog/hello_tokyo/
If "Kansai Branch" and "News" are set, it should become "/kansai/news/○○/"
By the way,
If "Blog" is set as a child category of "Tokyo Branch", it will become "/tokyo/blog/○○/", but

if you create "Blog" under "Kansai Branch" as well, the slug will be duplicated, resulting in "blog-kansai".

So, it seems we have to force it.
Using post_link
We will change the permalink using the "post_link" hook.
post_link | Hook | WordPress Developer Resources
Add the following to functions.php
// Hierarchical permalinks for multiple categories
function permalink_change_post($permalink, $post){
// Get post categories and store slugs in an array
$category = get_the_category($post->ID);
$category_slug = array();
foreach ($category as $cate){
array_push($category_slug, $cate->slug);
}
// Category 1
$cate_arr1 = array('tokyo', 'kansai');
// Category 2
$cate_arr2 = array('blog', 'news');
// Difference between "post categories" and "category 1, 2"
$diff_1 = array_intersect($cate_arr1, $category_slug);
$diff_2 = array_intersect($cate_arr2, $category_slug);
// When one of each category 1 and 2 is included
if(count($diff_1) === 1 && count($diff_2) === 1){
// Change permalink to hierarchical
$permalink = home_url('/'.$diff_1[0].'/'.$diff_2[0].'/'.$post->post_name.'/' );
}
return $permalink;
}
add_filter('post_link', 'permalink_change_post', 10, 2);
It's a bit messy, but
① First, get the categories of the current post.
② Define the slug of the category you want to be the parent on line 12.
③ Define the slug of the category you want to be the child on line 14.
When one category from ② and one from ③ are set for the current post,
the permalink will be changed to "/②/③/○○/".
Then, the permalink changed.

The URL didn't change just by refreshing the page, so open it again from a list or similar.





If this was helpful, we appreciate your support!
Any support received will be used for childcare.
Or support us by buying something from the buttons below
(You don't have to buy the linked product.)
Amazon
楽天市場
Yahoo!ショッピング
PR