Shorten the URL WordPress creates from a new post's title by removing words like "the", "and" and "how".
add_filter( 'wp_insert_post_data', function ( array $data, array $postarr ): array {
if ( 'post' !== $data['post_type'] || in_array( $data['post_status'], [ 'draft', 'pending', 'auto-draft', 'inherit' ], true ) ) {
return $data;
}
// Only touch slugs WordPress just generated: never change an existing or hand-typed one.
$existing = ! empty( $postarr['ID'] ) ? (string) get_post_field( 'post_name', $postarr['ID'] ) : '';
if ( '' !== $existing || $data['post_name'] !== sanitize_title( wp_unslash( $data['post_title'] ) ) ) {
return $data;
}
$stop = [ 'a', 'an', 'and', 'are', 'as', 'at', 'be', 'but', 'by', 'for', 'from', 'how', 'in', 'is', 'it', 'of', 'on', 'or', 'the', 'to', 'what', 'when', 'where', 'why', 'with', 'your' ];
$words = array_values( array_diff( explode( '-', $data['post_name'] ), $stop ) );
// Keep the original if removing stop words leaves too little.
if ( count( $words ) >= 3 ) {
$data['post_name'] = wp_unique_post_slug( implode( '-', $words ), (int) ( $postarr['ID'] ?? 0 ), $data['post_status'], $data['post_type'], (int) $data['post_parent'] );
}
return $data;
}, 10, 2 );
Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.
A title like “How to Choose the Best Running Shoes for Your Feet” becomes a long slug full of filler words. This snippet trims them, giving /choose-best-running-shoes-feet/, when the post is first published.
WordPress creates the slug from the title when a post is first published, then passes everything through wp_insert_post_data before saving. The snippet only acts on blog posts being published for the first time whose slug matches the title exactly, meaning WordPress made it automatically.
It removes common English stop words. If at least three words remain, it uses the shorter slug, made unique with wp_unique_post_slug(). Otherwise it keeps the original.
Create a post called “How to Make the Perfect Cup of Coffee” and publish it. The slug should be make-perfect-cup-coffee.