How can I get an url-friendly version of the post_title? I´m using anchor links for my posts on an archive page, and for the moment the posts get the post_ID as a hash tag but I would like to get the title instead as it would look nicer.

  • what code is used to generate these anchor links?
    – Michael
    Jun 28, 2012 at 22:27
  • I just set the ID of my post to the post_ID. Then I can anchor link to them with a link where the href is #post_ID. No funky code or anything...
    – Johan Dahl
    Jun 29, 2012 at 6:00

2 Answers 2


PHP has a function for url encoding that would probably work:

urlencode( get_the_title() );
  • Probably had better do: urlencode( get_the_title( $post->ID ) );
    – Pippin
    Jun 28, 2012 at 22:39
  • @pippin's right assuming you're outside of the loop.
    – mrwweb
    Jun 29, 2012 at 3:18
  • urlencode( get_the_title() ); gives me: S%C3%A4kerheten+f%C3%B6rst for the title "Säkerheten först". Not really good looking. I´m looking for something which gives me: "sakerheten-forst".
    – Johan Dahl
    Jun 29, 2012 at 6:09
  • To get that, I think you'll have to write a regex expression. Sadly, I'm terrible at those.
    – mrwweb
    Jun 29, 2012 at 20:17
  • 1
    @Johan why not use the slug then? Feb 4, 2016 at 10:52

If you want the short version with "-" between the words use the slug. If you don't want to use the slug use the function bellow:

    $new_url = sanitize_title(get_the_title());
    echo $new_url;


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.