Automatically Remove Short Words From WP Permalinks
WordPress automatically saves a permalink for you when creating a new post. Most people edit this before publishing it to remove the low-value keywords from it, otherwise it would be a giant URL. For example:
- Guide: How to Repair a Roof on a Budget in 2024
in WordPress, the title they would choose by default is:
- /guide-how-to-repair-a-roof-on-a-budget-in-2024
With this functions.php code, it will remove any words that are 4 characters or less. It would become:
- /guide-repair-roof-budget
Pretty handy, right? Here's the code; simply plop it at the bottom of your functions.php file in your theme:
/*
* Removes short low-value words from the automatically-generated permalink
*/
function modify_draft_permalinks($data) {
if ($data['post_status'] != 'draft') {
return $data;
}
$title = $data['post_title'];
$small_words = '/\b(\w{1,3})\b/'; // Match words of 1 to 3 characters.
$new_title = preg_replace($small_words, '', $title);
$new_title = sanitize_title_with_dashes($new_title);
$data['post_name'] = $new_title;
return $data;
}
add_filter('wp_insert_post_data', 'modify_draft_permalinks', 10, 1);
Addressing potential questions:
Will this mess with my exisiting permalinks?
No, this is only functions when creating new posts that are still in the "Draft" state. They are for posts that are not published yet.
WordPress will autosave your work after 30 seconds or so, and they choose a permalink for you. This replaces that functionality and chooses a shorter, better permalink.
Can I still set my own permalink?
Yes, this just affects the automatic recommendation. You can still replace it manually and this code won't overwrite your changes.
Can I change the length?
Yes. By default, this removes any word that is 3 characters long or smaller.
If you want to make it only remove 2 characters words or less, for instance, then change the $small_words line to:
$small_words = '/\b(\w{1,2})\b/';
What's the point?
Many of our clients write their own content in addition to our work that we do for their sites. Unfortunately they don't always optimize their permalinks, so you end up with gigantic URLs.
This is a nice set-it-and-forget-it thing that improves the default WordPress functionality by trimming low-value words from URLs.
September 24, 2024
Super helpful tip with the functions.php code! Can this be changed to work with custom post types??
September 27, 2024
Hey there annalee!
So happy you found the tip helpful! Yes you can definitely change the code to work with custom post types. You just need to add a few lines to target those post types specifically.
I usually try out different plugins that handle custom post types pretty well. Trying those might save you a lot of time and effort!
Hope that helps! Need more details? Just ask!