WordPress function to get post/page slug

August 23, 2012 at 5:37 pm

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!

Tags: