最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Remove words from permalink when saving post automatically?

programmeradmin1浏览0评论

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.

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.

Share Improve this question edited May 15, 2019 at 13:26 the 1,5682 gold badges13 silver badges32 bronze badges asked Jan 18, 2019 at 11:05 Michael RogersMichael Rogers 5498 silver badges37 bronze badges 1
  • Related: wordpress.stackexchange/questions/192564/… – Jos Commented Jan 18, 2019 at 11:13
Add a comment  | 

1 Answer 1

Reset to default 3

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' );

    }
}
发布评论

评论列表(0)

  1. 暂无评论