Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.