Tags

, , ,

wordpress_slug_page_of_posts
In WordPress, when one publishes a new post/page, the slug of that post/page sanitizes the post title and creates the slug.

For example: if the new post/page title is “What A Beautiful Morning” then the slug would be “what-a-beautiful-morning” which seems very relevant,
but the problem/annoyance is when we try to edit the post/page title and the slug doesn’t change. For example if we for some reason change the same above post/page title to “What A Beautiful Evening” and update, we would see the slug would still be the same old “what-a-beautiful-morning” which is irrelevant now.

But since this a single change we can go ahead and do it, but this can be even more annoying and painful when you are using a duplicate post plug-in to create new post/page from the old ones by making some small changes in the post/page like post/page title. Here you have a huge numbers of slugs to deal with and this can be a real pain.

But to avoid all the above, I have here come up with a tip to change the slug on the fly with the post/page update and save the user from the tired and boring job of manually editing the slug(s).

We will be using a filter provided by WordPress ie: “wp_insert_post_data“. This filter hook is called by the wp_insert_post function prior to inserting
into or updating the database.

add_filter( 'wp_insert_post_data', 'my_function', 50, 2 );
function my_function( $data, $postarr ) {

    if ( !in_array( $data['post_status'], array( 'draft', 'pending', 'auto-draft' ) ) ) {
        $data['post_name'] = sanitize_title( $data['post_title'] );
    }
    return $data;
}

The above would change the slug for all the posts/pages with the post status excluding draft, pending, auto-draft. You can make the changes as per your need.

If you want to make the change only for a particular post/page then you can put a condition to do so.
For example: lets do it only for Home page

add_filter( 'wp_insert_post_data', 'my_function', 50, 2 );
function my_function( $data, $postarr ) {

    if ( !in_array( $data['post_status'], array( 'draft', 'pending', 'auto-draft' ) ) ) {
        if( HOME_PAGE_ID == $postarr['ID']) {
            $data['post_name'] = sanitize_title( $data['post_title'] );
        }
    }
    return $data;
}

The ‘HOME_PAGE_ID’ is a constant which can be defined with the home page id.

So the above saves you the time and pain of manually editing the slugs.

So now its time to do some smart coding 🙂