Posted Post

Posted People, Posted Life.

Ultimate WP Post Name URL Sanitize Solution

Few days ago, I was not satisfied with the ugly URL of some post, so I hacked “sanitize_title” function. After I said that time, I also not satisfied with super-long URL and want short them. After short WP category permalink structure today, I put more hacked code in sanitize_title function for short URL. Anyhow, shit happens and I noticed sanitize_title function also used almost everywhere, special when normal visitor visit and process the URL. I don’t want to explain how this mess up, just forget it.

So, I need new method of short and nice URL for article post. I need find a place for “apply_filters” or “do_action“, after quite long time track from /wp-admin/post.php, finally I found at sanitize_post_field function, $value = apply_filters(”pre_$field”, $value); to pretreat all submit data.

Here is my filter:

function postedpost_sanitize_post_name( $post_name ){
if ( empty($post_name) || ( $post_name == ”) ) {
//most of time, new submit article do not have post_name, so get data from post_title
if ( isset( $_POST['post_title'] ) )
$post_name = $_POST['post_title'];
else
$post_name = ”;
}
$post_name = strip_tags($post_name); // remove tags…
$post_name = preg_replace(”/[^a-z0-9]+/i”, ” “, strtolower($post_name)); //remove all non-English code
$post_name = trim(preg_replace(”/\s+/i”, ” “, $post_name));
if (strlen($post_name) > 65) { // if length too long
$post_name = preg_replace(”/ [a-z0-9]{1,2} | \d+ | about | after | all | also | and | another | any | are | because | been | before | being | between | both | but | came | can | come | could | did | each | for | from | get | got | has | had | have | her | here | him | himself | his | how | into | like | make | many | might | more | most | much | must | never | now | only | other | our | out | over | said | same | see | should | since | some | still | such | take | than | that | the | their | them | then | there | these | they | this | those | through | too | under | very | was | way | well | were | what | where | when | which | while | who | with | would | you | your /i”, ” “, $post_name); //first try remove some common words, for SEO :)
$post_name = trim(preg_replace(”/ {2,}/i”, ” “, $post_name));
if (strlen($post_name) > 65) { //if still long
$post_name = substr($post_name, 0, 65);
$post_name = substr($post_name, 0, strrpos($post_name, ” “));
}
}
return $post_name;
}
add_filter(’pre_post_name’, ‘postedpost_sanitize_post_name’);

That’s all, works well. Btw, for English title only.

No comments yet »

Your comment

HTML-Tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>