Custom post types are a powerful feature of WordPress that allow you to create custom content types. For example, you could create a custom post type for products, services, or events.
If you have a parent-child relationship between your custom post types, you may want to set up a permalink structure that fetches all children custom posts with the parent post. This can be useful for creating archives of related content.
To set up a permalink structure for child custom posts, you will need to use the following code in your theme’s functions.php file:
function custom_post_type_permalink($post_link, $post, $leavename) {
if ($post->post_type == 'child-post-type') {
$parent_post = get_post($post->post_parent);
$post_link = str_replace($parent_post->post_name, $parent_post->post_name . '/%postname%/', $post_link);
}
return $post_link;
}
add_filter('post_type_link', 'custom_post_type_permalink', 10, 3);
This code will add the parent post’s slug to the permalink of all child custom posts. For example, if your parent post has the slug “products” and your child post has the slug “product-1”, the permalink for the child post will be “products/product-1”.
Once you have added this code to your theme, you will need to flush your permalinks. You can do this by going to Settings > Permalinks and clicking the Save Changes button.
After you have flushed your permalinks, the new permalink structure will be applied to all child custom posts.