The the_permalink WordPress PHP filter alters the display of the permalink for the current post.
Usage
add_filter('the_permalink', 'your_custom_function', 10, 2);
function your_custom_function($permalink, $post) {
// your custom code here
return $permalink;
}
Parameters
$permalink(string) – The permalink for the current post.$post(int|WP_Post) – Post ID, WP_Post object, or 0. Default 0.
Returns
The modified permalink for the current post.
More information
See WordPress Developer Resources: the_permalink
Important: The output of the functions get_permalink() or get_the_permalink() is not filtered.
Examples
Add a Custom Query Parameter
Add a custom query parameter ref to the permalink.
add_filter('the_permalink', 'add_custom_query_parameter', 10, 2);
function add_custom_query_parameter($permalink, $post) {
$permalink = add_query_arg('ref', 'custom_value', $permalink);
return $permalink;
}
Add a UTM Campaign
Add a UTM campaign to the permalink for tracking.
add_filter('the_permalink', 'add_utm_campaign', 10, 2);
function add_utm_campaign($permalink, $post) {
$permalink = add_query_arg('utm_campaign', 'your_campaign', $permalink);
return $permalink;
}
Change Permalink to Custom URL
Redirect post permalinks to an external URL stored in a custom field.
add_filter('the_permalink', 'redirect_to_custom_url', 10, 2);
function redirect_to_custom_url($permalink, $post) {
$custom_url = get_post_meta($post->ID, 'custom_url', true);
if (!empty($custom_url)) {
$permalink = $custom_url;
}
return $permalink;
}
Remove Category Base from Permalink
Remove the category base from the permalink.
add_filter('the_permalink', 'remove_category_base_from_permalink', 10, 2);
function remove_category_base_from_permalink($permalink, $post) {
$category_base = get_option('category_base');
if ($category_base) {
$permalink = str_replace($category_base . '/', '', $permalink);
}
return $permalink;
}
Make Permalink Hashed
Generate a hashed permalink based on the post ID.
add_filter('the_permalink', 'hashed_permalink', 10, 2);
function hashed_permalink($permalink, $post) {
$hashed_permalink = home_url('/') . '#' . md5($post->ID);
return $hashed_permalink;
}