The ‘pre_post_link’ WordPress filter allows you to modify the permalink structure for a specific post before the tokens are replaced.
This filter works only with posts that have a post_type
of ‘post’.
Usage
To use this filter, you need to create a custom function and hook it to the 'pre_post_link'
filter. Here’s a code example:
function my_custom_permalink( $permalink, $post, $leavename ) { // Your code here return $permalink; } add_filter( 'pre_post_link', 'my_custom_permalink', 10, 3 );
Parameters
$permalink (string)
: The site’s permalink structure.$post (WP_Post)
: The post for which the permalink is being generated.$leavename (bool)
: Whether to keep the post name in the permalink.
Examples
Add a Custom Prefix to Permalink
function add_custom_prefix( $permalink, $post, $leavename ) { return '/custom-prefix' . $permalink; } add_filter( 'pre_post_link', 'add_custom_prefix', 10, 3 );
In this example, the function add_custom_prefix
adds a custom prefix to the permalink structure.
Add Post ID to Permalink
function add_post_id_to_permalink( $permalink, $post, $leavename ) { return $permalink . '-' . $post->ID; } add_filter( 'pre_post_link', 'add_post_id_to_permalink', 10, 3 );
This example adds the post ID to the end of the permalink structure.
Add Category Name to Permalink
function add_category_to_permalink( $permalink, $post, $leavename ) { $category = get_the_category( $post->ID ); return '/' . $category[0]->slug . $permalink; } add_filter( 'pre_post_link', 'add_category_to_permalink', 10, 3 );
In this example, we add the post’s first category name to the permalink structure.
Change Permalink for Specific Post ID
function change_permalink_for_specific_post( $permalink, $post, $leavename ) { if ( $post->ID == 123 ) { return '/special-permalink'; } return $permalink; } add_filter( 'pre_post_link', 'change_permalink_for_specific_post', 10, 3 );
In this scenario, we change the permalink structure for a specific post with ID 123.
Remove Dates from Permalink
function remove_dates_from_permalink( $permalink, $post, $leavename ) { $permalink = preg_replace( '/(\d{4}\/\d{2}\/\d{2}\/)/', '', $permalink ); return $permalink; } add_filter( 'pre_post_link', 'remove_dates_from_permalink', 10, 3 );
This example removes dates (YYYY/MM/DD) from the permalink structure.