How do I use underscore in a wordpress permalink

WordPress converts my post title to a permalink which is great, the only thing is that I want underscores instead of hyphens, is there a quick solution?

Related posts

Leave a Reply

5 comments

  1. Hunt down the following file: wp-includes/formatting.php

    Jump down to the sanitize_title_with_dashes function. You’ll find this section of code inside:

    $title = strtolower($title);
    $title = preg_replace('/&.+?;/', '', $title); // kill entities
    $title = str_replace('.', '-', $title);
    $title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
    $title = preg_replace('/s+/', '-', $title);
    $title = preg_replace('|-+|', '-', $title);
    $title = trim($title, '-');
    

    Swap out all of the dashes/hyphens (-) for underscores (_) like so:

    $title = strtolower($title);
    $title = preg_replace('/&.+?;/', '', $title); // kill entities
    $title = str_replace('.', '_', $title);
    $title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
    $title = preg_replace('/s+/', '_', $title);
    $title = preg_replace('|-+|', '_', $title);
    $title = trim($title, '_');
    

    Note that any posts you’ve created before this change, and rely on the %postname% permalink structure tag, will be broken.

    In that case you’ll need to go back and republish those post so the dashes are swapped out for the underscores. Or just write yourself a little SQL to replace them.

  2. I wouldn’t do it mainly because of SEO’s issues.

    Is there any specific reason for you to do it? Every solution I read here is about hacking wordpress core, and everytime you update your system you’re going to edit all these files again. (In fact, 2.8.6 was avaiable just yesterday. If you’re using and old version, you would need to change two times).

  3. Look for function sanitize_title_with_dashes() in wp-includes/formatting.php

    Change the calls to preg_replace there to use underscores instead of hypens.

  4. I would not recommend changing core wordpress files, you will lose your work as soon as you upgrade your site. You can make a plugin, or put this in your theme’s functions.php file.

    add_filter( 'sanitize_title', 'dashes_to_underscore' );
    function dashes_to_underscore( $title ){
        return str_replace( '-', '_', $title );
    }
    
  5. function sanitize_title_with_underscore( $title )
    {
        $text_to_transform =   sanitize_title_with_dashes( $title);
        return str_replace( '-', '_', $text_to_transform );
    }