How can I automatically remove certain words from the automatically generated permalink (it uses %postname%
).
For example: if a new post is created with the title:
How to remove certain words from the WordPress permalink
I want to have an array of forbidden words like: certain
, permalink
And then the slug would be saved automatically as as:
How-to-remove-words-from-the-wordpress
I don’t want to affect old posts URLs just the new published ones.
I found plugins but they are too heavy, with millions of functions I just want to know how to modify the permalink while saving the post.
To update the slug of posts when they’re published, hook to save_post
action as in this answer. Also use sanitize_title() to perform the needed sensitization:
add_action( 'save_post', 'wpse325979_save_post_callback', 10, 2 );
function wpse325979_save_post_callback( $post_id, $post ) {
// verify post is not a revision
if ( ! wp_is_post_revision( $post_id ) ) {
// unhook this function to prevent infinite looping
remove_action( 'save_post', 'wpse325979_save_post_callback' );
$title = $post->post_title;
// remove forbidden keywords
$forbidden = array('~certain~i', '~permalink~i'); //i modifier for case insensitive
$title = preg_replace($forbidden, '', $title);
// update the post slug
$slug = sanitize_title($title);
wp_update_post( array(
'ID' => $post_id,
'post_name' => $slug
));
// re-hook this function
add_action( 'save_post', 'wpse325979_save_post_callback' );
}
}