Is there a way to overwrite WP slug validation function to only accept basic characters ([A-Z0-9-]) as I want to avoid the long encoded permlink.



For now I used the sanitize_title filter, and removed all unwanted characters, which forces my users to use only [a-z0-9-] as a valid input for titles.

## Allow only [a-z0-9-] in the slug
function my_clear_title($title) {

    $pattern = '/[^a-z_0-9- ]/i';
    $replace_with = '';
    return preg_replace($pattern, $replace_with, $title);
add_filter('sanitize_title', 'my_clear_title', 3, 1);
  • I had to use a higher priority (3) to make sure my filter will run before wordpress builtin filters.
| improve this answer | |
  • IIRC sanitize_title has a context parameter which you might want to check to make sure you are not sanitizing things that are not slugs in this way. – Mark Kaplun Apr 21 '16 at 15:37
  • Thanks @MarkKaplun for the input, I looked on the documentations and the source for this function, the context parameter is more like a "when" and not "what" parameter and it default to save. from my testing it looks like it works for permalinks as well on names for tags and category's (which is great) – Rabin Apr 21 '16 at 21:27
  • In one of the plugin I wrote I use a context of my own to avoid this type of sanitation..... You really should check the context – Mark Kaplun Apr 21 '16 at 21:31
  • you mean to explicitly check that the context is on save ? and only then apply my filter ? – Rabin Apr 22 '16 at 9:14

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.