You could do this like saving post meta. You would unhook out of the current hook and update the post, if you don’t do that you will end up in an infinite loop:
/**
* Save Custom Data
* @param int $post_id
* @param Post Object $post
*/
function save_custom_meta_boxes( $post_id, $post ) {
// If we're not in the right place, bailout
if( ! isset( $post ) || wp_is_post_autosave( $post ) || wp_is_post_revision( $post ) ) {
return $post_id;
}
// `members` Type Metaboxes
if( 'members' == $post->post_type ) {
// Update Post Slug
if( isset( $_POST['member_user'] ) && ! empty( $_POST['member_user'] ) ) {
remove_action( 'save_post', 'save_custom_meta_boxes' );
wp_update_post( array( 'ID' => $post_id, 'post_name' => sanitize_title( $_POST['member_user'] ) ) );
add_action( 'save_post', 'save_custom_meta_boxes' );
}
}
}
add_action( 'save_post', 'save_custom_meta_boxes', 10, 2 );
IF the user has set a value into the member_user
field we will remove the current action, update the post to the new slug using the same field, and rehook the action to continue processing any other post meta values. We take advantage of sanitize_title()
to ensure the user doesn’t add anything malicious.