tags:

views:

28

answers:

3

How to sanitize the post_name value before inserting in WordPress?

A: 

Some solution might be found at http://postedpost.com/2008/06/23/ultimate-wordpress-post-name-url-sanitize-solution/

Also, you might want to do it as follows:

$special_chars = array("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}");
$post_name = str_replace(' ', '-', str_replace($special_chars, '', strtolower($post_name)));
Alex Polo
A: 

Simple:

$post_title = sanitize_title_with_dashes($post_title);

But WordPress does this for you already. I assume you need it for something different?

MikeSchinkel
sanitize_title($post_title); works as well
Anraiki
@Anraiki: But it doesn't do it with *dashes*. ;-)Seriously though, `sanitize_title()` leaves spaces which you don't want in `post_name`.
MikeSchinkel
That's odd. http://codex.wordpress.org/Function_Reference/sanitize_title Unless, I am reading it wrong with the example they are showing there. 'This Long Title is what My Post or Page might be' -> 'this-long-title-is-what-my-post-or-page-might-be'
Anraiki
@Anaraiki - My bad. I read the code `sanitize_title()` and assumed that the filter called in the code was to allow plugins to filter but instead core actually uses it. `sanitize_title()` first calls `strip_tags()` and then invokes a filter which ultimately calls `sanitize_title_with_dashes()`. So unless there's a concern that HTML will creep in then `sanitize_title_with_dashes()` is a tiny bit more performant and probably the better choice.
MikeSchinkel
A: 

I'm guessing you're sanitizing by direct SQL insertion. Instead, consider using wp_post_insert() in your insertion script.

$new_post_id = wp_insert_post(array(
  'post_title' => "This <open_tag insane title thing<b>LOL!;drop table `bobby`;"
));

At this point, you just worry about your title - and not the slug, post name, etc. WP will take care of the rest and (at least security) sanitization. The slug, as demonstrated in the screenshot, becomes fairly usable.

alt text

This function can be used by simply doing include( "wp-config.php" ); and going about your business without any other PHP overhead.

If you are dealing with some funky titles to begin with, a simple strip_tags(trim()) might do the trick. Otherwise, you've got other problems to deal with ;-)

pp19dd