
When coding or styling a theme, it can be very useful to be able to get the slug of the current post or page, for example to create a css class. Here’s an easy function to get the slug from the current post or page.

When coding or styling a theme, it can be very useful to be able to get the slug of the current post or page, for example to create a css class. Here’s an easy function to get the slug from the current post or page.
Here's the function. Copy it and paste it into your functions.php file:
function the_slug() {
$post_data = get_post($post->ID, ARRAY_A);
$slug = $post_data['post_name'];
return $slug;
}
Once done, simply call the function within the loop to get the post or page slug.
<?php echo the_slug(); ?>
Thanks to Maidul for the function!
5 Responses
Or, the following would do the same thing but without needing to call get_post and perform a database lookup.
function get_the_slug() {
global $post;
return $post->post_name;
}
function the_slug() {
echo get_the_slug()
}
Um, am I missing something?
If you are within the loop anyway why not just use $post->post_name?
Also, I have no idea what this means:
“Once you saved the file, you’re now able to use only one database”
Randy, you’re not missing anything
Ryan, prefix your function names to avoid conflicts with other plugins/themes and future versions of WordPress.
WPRecipes, as Randy pointed out, you can just use the $post global inside the loop and output $post->post_name all you want. Also, as a convention, the_* functions should output, get_the_* functions should return. And finally, prefix all the thinks.
Cheers,
Konstantin
good post.
@Kovshenin thanks for this useful information.
Randy + Konstantin: The two functions I added were purely samples to show that, should you want to create a seperate function to return the Post slug (rather then directly referencing $post->post_name), you could do it without calling the get_post() function – and so remove the additional database call. Within my own production code I would always prefix the function names and check to see if they already exist.
Trackbacks: