Ever wanted to generate custom URLs in WordPress for your posts? Turns out it’s actually pretty simple.

In this post, I’m going to show you how to generate custom post URLs in WordPress with a few examples. I originally came across this while working on an invoicing system. Every time an invoice was modified a pdf would automatically be generated using the URL as the file name. Obviously, each pdf needed a custom file name. The solution was to generate a new URL on every update.

This is also useful for news site running updates on stories they previously covered with the same URL.

To keep it basic we’ll start with just adding time() to the URL.

function wp_custom_append_slug($data) {
	global $post_ID;
	
        $data['post_name'] = sanitize_title($data['post_title'], $post_ID);
	$data['post_name'] .= time();
	
	return $data; 
} 
add_filter('wp_insert_post_data', 'wp_custom_append_slug', 10);

Now before you speed off let’s just make sure we double check a few things. First, check if the post has a title and if the post is actually published.

function wp_custom_append_slug($data) {
	global $post_ID;
	
	if (!empty($data['post_name']) && $data['post_status'] == "publish") {
		$data['post_name'] = sanitize_title($data['post_title'], $post_ID);
$data['post_name'] .= time();
	}
	
	return $data; 
} 
add_filter('wp_insert_post_data', 'wp_custom_append_slug', 10);

Next, make sure this function only runs when you publish a post and not every time you update a post. This if statement simply checks if the post date matches the last modified date. If the last modified date is past the post date the URL will not change.

function wp_custom_append_slug($data) {
	global $post_ID;
	
	if (!empty($data['post_name']) && $data['post_status'] == "publish") {
		if( $data['post_date_gmt'] == $data['post_modified_gmt'] ) {
			$data['post_name'] = sanitize_title($data['post_title'], $post_ID);
$data['post_name'] .= time();
		}
	}
	
	return $data; 
} 
add_filter('wp_insert_post_data', 'wp_custom_append_slug', 10);

So how else can this be used?

Here are a few examples. Simply switch out the time() function with any alternative.

// time as a Unix timestamp
$data['post_name'] .= time();

// date as j Y (day of the month - year)
$data['post_name'] .= date('j-Y');

// random number between 10 & 100
$data['post_name'] .= rand(10,100);

// adds site name
$data['post_name'] .= get_bloginfo('name');

Of course, you can add almost anything to your custom URLs. Hopefully, this post has helped you.