Skip to content

Instantly share code, notes, and snippets.

@donohoe
Last active December 18, 2022 20:30
Show Gist options
  • Save donohoe/4766b8a20cc6573de3dd3cb59df9fc32 to your computer and use it in GitHub Desktop.
Save donohoe/4766b8a20cc6573de3dd3cb59df9fc32 to your computer and use it in GitHub Desktop.
/*
Alter default Post slug upon first save
Reference:
https://wordpress.stackexchange.com/questions/217075/change-slug-on-post-creation/217101#217101
*/
function slug_save_post_callback( $post_id, $post, $update ) {
if (empty($post->post_title) || !empty($post->post_name)) {
return;
}
if ($post->post_type != 'post' || $post->post_status == 'auto-draft') {
return;
}
$slug = preg_replace("/[^A-Za-z0-9 ]/", '', $post->post_title);
$slug = trim(preg_replace("/(^|\s+)(\D(\s+|$))+/", ' ', $slug));
$remove_list = array(
'after', 'an', 'and', 'are', 'around', 'as', 'at', 'back', 'be', 'behind', 'being', 'big', 'biggest', 'but', 'by',
'can', 'cant', 'changed', 'did', 'do', 'drive', 'far', 'for', 'from', 'get', 'going', 'got', 'grab', 'great',
'had', 'has', 'hasnt', 'have', 'heres', 'his', 'how', 'in', 'into', 'is', 'its', 'just',
'knows', 'like', 'means', 'more', 'most', 'need', 'needs', 'new', 'not',
'of', 'off', 'on', 'only', 'or', 'ok', 'says', 'see', 'set', 'stay', 'still', 'story',
'than', 'that', 'the', 'their', 'theyre', 'this', 'to', 'use', 'used', 'using',
'want', 'we', 'what', 'whats', 'when', 'where', 'who', 'whom', 'why', 'will', 'with', 'wont', 'you'
);
foreach($remove_list as $word) {
$slug = preg_replace("/\b$word\b/i", "", $slug);
}
$slug = explode("-", sanitize_title($slug));
$slug = implode("-", array_slice($slug, 0, 6));
if ($slug == $post->post_name) {
return;
}
// Unhook this function to prevent infinite looping, restore it later
remove_action( 'save_post', 'slug_save_post_callback', 5, 3 );
wp_update_post(array(
'ID' => $post_id,
'post_name' => $slug
));
add_action( 'save_post', 'slug_save_post_callback', 5, 3 );
clean_post_cache($post_id);
}
add_action( 'save_post', 'slug_save_post_callback', 5, 3 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment