Shorter Post Slugs Without Stop Words
Removes filler words such as "the", "and" or "how" from automatically created post slugs and caps their length, giving shorter, cleaner URLs.
Opens WPIDE on
Code
// Words removed from new slugs, and the maximum number of words kept.
$wpide_stop_words = array( 'a', 'an', 'and', 'are', 'as', 'at', 'be', 'by', 'for', 'from', 'how', 'in', 'into', 'is', 'it', 'of', 'on', 'or', 'our', 'the', 'this', 'that', 'to', 'what', 'when', 'why', 'with', 'you', 'your' );
$wpide_slug_max_words = 6;
add_filter( 'wp_insert_post_data', function ( $data, $postarr ) use ( $wpide_stop_words, $wpide_slug_max_words ) {
if ( ! empty( $postarr['post_name'] ) || empty( $data['post_name'] ) || in_array( $data['post_status'], array( 'draft', 'auto-draft', 'pending', 'inherit', 'trash' ), true ) || 'attachment' === $data['post_type'] ) {
return $data;
}
$words = explode( '-', $data['post_name'] );
$kept = array_values( array_diff( $words, $wpide_stop_words ) );
if ( count( $kept ) < 2 ) {
return $data;
}
$slug = implode( '-', array_slice( $kept, 0, $wpide_slug_max_words ) );
if ( $slug !== $data['post_name'] ) {
$data['post_name'] = wp_unique_post_slug( $slug, (int) ( $postarr['ID'] ?? 0 ), $data['post_status'], $data['post_type'], (int) $data['post_parent'] );
}
return $data;
}, 10, 2 );
Notes
Only slugs WordPress creates from the title on first publish are changed; slugs you edit by hand are kept. Edit the word list for other languages.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.