Using WordPress ‘post_link’ PHP filter

The post_link WordPress PHP filter allows you to modify the permalink of a post.

Usage

add_filter('post_link', 'your_function_name', 10, 3);

function your_function_name($permalink, $post, $leavename) {
    // your custom code here
    return $permalink;
}

Parameters

  • $permalink (string) – The post’s permalink.
  • $post (WP_Post) – The post in question.
  • $leavename (bool) – Whether to keep the post name.

More information

See WordPress Developer Resources: post_link

Examples

Add a prefix to post permalinks

This example adds a custom prefix to the post permalinks.

add_filter('post_link', 'add_prefix_to_permalink', 10, 3);

function add_prefix_to_permalink($permalink, $post, $leavename) {
    $prefix = 'my-prefix';
    $permalink = str_replace(home_url('/'), home_url('/') . $prefix . '/', $permalink);
    return $permalink;
}

Append the post ID to the permalink

This example appends the post ID to the post’s permalink.

add_filter('post_link', 'append_post_id_to_permalink', 10, 3);

function append_post_id_to_permalink($permalink, $post, $leavename) {
    $permalink .= '-' . $post->ID;
    return $permalink;
}

This example changes the permalink structure for posts in the ‘news’ category.

add_filter('post_link', 'change_permalink_for_news_category', 10, 3);

function change_permalink_for_news_category($permalink, $post, $leavename) {
    if (in_category('news', $post)) {
        $permalink = home_url('/') . 'news/' . $post->post_name;
    }
    return $permalink;
}

This example makes all post permalinks uppercase.

add_filter('post_link', 'uppercase_permalink', 10, 3);

function uppercase_permalink($permalink, $post, $leavename) {
    $permalink = strtoupper($permalink);
    return $permalink;
}

This example removes the date from the post permalink.

add_filter('post_link', 'remove_date_from_permalink', 10, 3);

function remove_date_from_permalink($permalink, $post, $leavename) {
    $permalink = preg_replace('/\d{4}\/\d{2}\//', '', $permalink);
    return $permalink;
}