Get post slug function

Taken from: http://www.tcbarrett.com/2011/09/wordpress-the_slug-get-post-slug-function/

Using basename() and get_permalink() to retrieve post slug

</pre>
<?php echo( basename(get_permalink()) ); ?>
<pre>

Using global $post object to retrieve post slug

</pre>
<?php global $post; echo $post->post_name; ?>
<pre>

 

Fully hookable function to retrieve the post slug


function the_slug($echo=true){
 $slug = basename(get_permalink());
 do_action('before_slug', $slug);
 $slug = apply_filters('slug_filter', $slug);
 if( $echo ) echo $slug;
 do_action('after_slug', $slug);
 return $slug;
}

This provides you with a simple way retrieve and display the post slug. I find this useful for applying unique CSS ids and classes to my HTML mark up.


<div id="some-post-container-<?php the_slug();?>">
 Lorem whatsit here
</div>

Revisions

No comments yet.

Leave a Reply