Auto-Sync Post Slug with Title for a Custom Post Type in WordPress

How to update the slug automatically after the title changes

We have a custom post type that is not shown on the site and in search, i.e. 'publicly_queryable' => false. For such a post type the admin does not show the permalink editor, so the slug cannot be edited there. But we use the slug in other places, for example to build anchors or to find the posts in code. The problem is that after the title is edited, the slug stays the old one. So we need to update the slug when the title is updated.

Problem: Automatically update the slug of a custom post type with the latest title.

Solution: Set the slug from the title right before the post is saved, with the wp_insert_post_data filter. In this example the post type is nominees.

<?php
// Keep the slug of 'nominees' in sync with the title
add_filter( 'wp_insert_post_data', 'nominees_slug_from_title', 10, 2 );

function nominees_slug_from_title( $data, $postarr ) {
    if ( 'nominees' !== $data['post_type'] || in_array( $data['post_status'], array( 'draft', 'auto-draft', 'trash' ), true ) ) {
        return $data;
    }

    $data['post_name'] = wp_unique_post_slug(
        sanitize_title( $data['post_title'] ),
        isset( $postarr['ID'] ) ? $postarr['ID'] : 0,
        $data['post_status'],
        $data['post_type'],
        $data['post_parent']
    );

    return $data;
}

The filter changes the data before it is written to the database, so there is no second save and no recursion, which you get with wp_update_post() inside save_post. wp_unique_post_slug() adds -2, -3 if another nominee has the same title.

Existing posts

The filter works only when a post is saved. For the posts created before, run this once (for example, temporarily in functions.php, then open any admin page and remove the code):

<?php
add_action( 'admin_init', function () {
    $ids = get_posts( array(
        'post_type'      => 'nominees',
        'post_status'    => 'publish',
        'posts_per_page' => -1,
        'fields'         => 'ids',
    ) );

    foreach ( $ids as $id ) {
        wp_update_post( array( 'ID' => $id ) ); // the filter above sets the new slug
    }
} );

My first version did the same check for all posts on every admin page load, in admin_enqueue_scripts. It works, but on hundreds of posts it noticeably slows down the dashboard.

NOTE: Use this only for post types without public URLs. For public posts a slug that changes with the title breaks old links and bookmarks.

Sources:

  1. https://wordpress.stackexchange.com/questions/295727/automatically-update-slug-with-latest-title-within-custom-post-type