How to automatically update slug

We have custom post type, that doesn’t appear in the search results ie ‘publicly_queryable’ => true, it’s mean, that URL this custom post type can’t be edited from admin dashboard. However we have places where we use this slug and we need have possible somehow can be edit. Problem is that after edit title, that slug will not change. Therefore we need to update slug after post title update.

Automatically update slug with latest title within custom post type

Problem: Automatically update slug with latest title within custom post type

Solution:

<?php
// Automatically update slug with latest title
add_action( 'admin_enqueue_scripts', 'force_update_post_slug' );
	
function force_update_post_slug() {
	$args = [
		'posts_per_page' => -1,
		'post_type' => 'nominees',
		'fields' => 'ids',
		'no_found_rows' => true,
	];
		
	$posts_ids = new WP_Query( $args );
	
	if ( $posts_ids ) {
		foreach ( $posts_ids as $posts_id ) {
		// Check the slug and run an update if necessary
		$new_slug = sanitize_title( get_the_title( $posts_id ) );
				
		if ( basename( get_permalink( $posts_id ) ) != $new_slug ) {
			wp_update_post(
				[
		    		'ID' => get_the_ID( $posts_id ),
					'post_name' => $new_slug,
				]
				);
			}
		}
	}
}

Sources:

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

Leave Comment

Your email address will not be published.