Get Post/Page Slug Using WordPress Function

This WordPress tip is from freelance web developer Maidul of Techsloution4u. When you’re creating a WordPress theme you might want to create some custom classes like CSS. This is where getting the slug of the current post can be very useful, which is what Maidul’s snippet does for you.

ScreenHunter 117 Sep. 03 09.47 Get Post/Page Slug Using WordPress Function
Simply copy and paste the following code below to your functions.php file:

function the_slug() {
 $post_data = get_post($post->ID, ARRAY_A);
 $slug = $post_data['post_name'];
 return $slug; 
}

After you’ve done that, just call the function within the loop to get the post or page slug.

// Put where you want to show in page or single etc. Use for custom class for each page
<?php echo the_slug(); ?>

And that’s all it takes to do it! I hope a lot of you benefit from this little snippet.

Incoming search terms for the article:

Related Posts

Creating a Psychedelic Art Effect in Your Portraits

EWWW Image Optimizer

Inspirational Photo Retouches By Cristian Girotto

Create Your Own Sticker Design Via Photoshop