Categories
Coding

The Post Slug

While within The Loop, WordPress provides many functions to quickly access the properties of the Post – but it doesn’t include a built-in function to get the slug for the current Post (although, admittedly, you could simply use $post->post_name).  This functionality can be easily included by adding the following two mini-functions within the functions.php file. function get_the_slug() { global $post; return […]

While within The Loop, WordPress provides many functions to quickly access the properties of the Post – but it doesn’t include a built-in function to get the slug for the current Post (although, admittedly, you could simply use $post->post_name).  This functionality can be easily included by adding the following two mini-functions within the functions.php file.

function get_the_slug() {
	global $post;
	return $post->post_name;
}

function the_slug() {
	echo get_the_slug();
}

Update (26 August 2012)

To be absolutely correct, to avoid possible conflicts with other core WordPress or third-party functions, the two sample functions should really be prefixed with a unique identifier, e.g. cornflowerdesign_get_the_post(). I would also recommend wrapping the functions with a function_exists() check, like so.

if ( !function_exists( 'cornflowerdesign_get_the_slug' ) ) {
	function cornflowerdesign_get_the_slug() {
		global $post;
		return $post->post_name;
	}
}