[solved] Slug as string (9 posts)

  1. Leodes
    Posted 8 years ago #

    I just wanted to share the solution to a problem that occurred to me and obviously many others. While searching the forums for a way to post the slug in my templates all I found at first was the suggestion to use the post title and run a sanitize function on it. Unfortunately that's not giving you the actual slug, only if you happened to name both identically. Digging a little in older posts I found something that was nearly what I was searching for.

    Here is a function that gives you the actual slug:

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

    Put the above code in your templates function.php, then you can use:

    <?php echo the_slug(); ?>

    in your template to get the slug.

    Hope this helps.

  2. chrishajer
    Posted 8 years ago #

    This is awesome, just what I was looking for. Very nice of you to share the solution.

  3. Jeremy Boggs
    Posted 8 years ago #

    Very handy, thanks!

  4. Tammy Hart
    Posted 8 years ago #

    awesome, thanks for much for this solution, was able to use the slug as a class for a div, giving me awesome css abilities. thanks!

  5. A somewhat simpler way:
    echo $post->post_name;

  6. thepete
    Posted 8 years ago #

    Leodes, thanks--that worked like a charm.

    Otto42, where did you find that? I was looking all over the place for just a bit of code that would do this. Ah well. Thanks to you both for sharing!!

  7. pilcrow
    Posted 8 years ago #

    Fabulous -- just what I needed!

  8. thepete
    Posted 8 years ago #

    This time I tried Otto42's suggestion and that works, too! Thanks both of you guys!

  9. Indojepang
    Posted 7 years ago #

    the advantage of the_slug from the post_name is u can edit the slug.
    for ex: i don't need space in the string.
    with post_name I can't do that.. or can i?

Topic Closed

This topic has been closed to new replies.

About this Topic