filters – Custom child page permalink
I’m trying to customize the permalink of some child pages.
I have this structure:
example.com/story/story-name-slug/chapter-slug/page-slug
And I’m trying to transforming that structure into this:
example.com/section/page-slug
But also I want to keep the other links active, so in the end I should have the following:
example.com/story
-> archive of all story;
example.com/story/story-name-slug
-> list of all chapters;
example.com/section/page-slug
-> page with customized url.
Keep in mind that example.com/story/story-name-slug/chapter-slug
is not a page that can be visited by users. It’s only used to archive the hierarchical relation between pages.
At the moment I got the url structure working with the following code in functions.php:
add_filter('page_link', 'custom_permalink', 10, 3);
add_filter('page_type_link', 'custom_permalink', 10, 3);
function custom_permalink($permalink, $post_id) {
$post = get_post($post_id);
$post_name = $post->post_name;
$id_chapter = $post->post_parent;
$id_story = wp_get_post_parent_id($id_chapter);
$id_stories = wp_get_post_parent_id($id_story);
if ($id_chapter !== 0 && $id_story !== 0 && $id_stories ) {
// the static base url is just for testing
$permalink = 'example.com/section/' . $post_name ;
} else {
$permalink = $permalink;
}
return $permalink;
}
This works but not as it shoudl, I get the right URLs on the right pages but when I visit those pages I get a 404 Error not found.
After some digging in the sql queris that get executed I think that the problem is that WP is selecting wp_posts.post_type="attachment"
instead of wp_posts.post_type="page"
.
I think that a rewrite rule is needed somewhere to specify in the sql query what to select, but this goes over my current capabilities.
If it’s needed I can provide all the queries that get executed on the page with and without the filter that I added.
Thanks!
Leave an answer