DISCLAIMER: this post is older than one year and may not be up to date with latest WordPress version.

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!


  1. 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()

  2. 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”

  3. 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.


  4. good post.
    @Kovshenin thanks for this useful information. 🙂

  5. 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.

Leave a Comment

Your email address will not be published. Required fields are marked *