The post_type_link WordPress PHP filter allows you to modify the permalink of a custom post type.
Usage
add_filter('post_type_link', 'your_custom_function', 10, 4);
function your_custom_function($post_link, $post, $leavename, $sample) {
// your custom code here
return $post_link;
}
Parameters
$post_link(string) – The post’s permalink.$post(WP_Post) – The post in question.$leavename(bool) – Whether to keep the post name.$sample(bool) – Is it a sample permalink.
More information
See WordPress Developer Resources: post_type_link
Examples
Remove date from permalink
Remove the date from the permalink for a custom post type called ‘events’.
add_filter('post_type_link', 'remove_date_from_permalink', 10, 4);
function remove_date_from_permalink($post_link, $post, $leavename, $sample) {
if ('events' === $post->post_type) {
$post_link = str_replace('%year%/%monthnum%/', '', $post_link);
}
return $post_link;
}
Add a custom prefix
Add a custom prefix to the permalink for a custom post type called ‘products’.
add_filter('post_type_link', 'add_custom_prefix', 10, 4);
function add_custom_prefix($post_link, $post, $leavename, $sample) {
if ('products' === $post->post_type) {
$post_link = str_replace('/products/', '/custom-prefix/products/', $post_link);
}
return $post_link;
}
Remove post type slug
Remove the post type slug from the permalink for a custom post type called ‘recipes’.
add_filter('post_type_link', 'remove_post_type_slug', 10, 4);
function remove_post_type_slug($post_link, $post, $leavename, $sample) {
if ('recipes' === $post->post_type) {
$post_link = str_replace('/recipes/', '/', $post_link);
}
return $post_link;
}
Add a custom post type base
Add a custom base to the permalink for a custom post type called ‘portfolio’.
add_filter('post_type_link', 'add_custom_post_type_base', 10, 4);
function add_custom_post_type_base($post_link, $post, $leavename, $sample) {
if ('portfolio' === $post->post_type) {
$post_link = str_replace('/portfolio/', '/our-work/portfolio/', $post_link);
}
return $post_link;
}
Append query string
Append a query string parameter to the permalink for a custom post type called ‘movies’.
add_filter('post_type_link', 'append_query_string', 10, 4);
function append_query_string($post_link, $post, $leavename, $sample) {
if ('movies' === $post->post_type) {
$post_link .= '?source=website';
}
return $post_link;
}