Skip Navigation

[Resolved] Update slug when post title is updated

This thread is resolved. Here is a description of the problem and solution.

Problem:
Client has custom code to update the post slug when the post title is updated with a post Edit Form, but it doesn't work.

Solution:
The code omitted the required post ID, see below: https://toolset.com/forums/topic/update-slug-when-post-title-is-updated/#post-1085557

100% of people find this useful.

This support ticket is created 6 years, 4 months ago. There's a good chance that you are reading advice that it now obsolete.

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

Sun Mon Tue Wed Thu Fri Sat
- 7:00 – 14:00 7:00 – 14:00 7:00 – 14:00 7:00 – 14:00 7:00 – 14:00 -
- 15:00 – 16:00 15:00 – 16:00 15:00 – 16:00 15:00 – 16:00 15:00 – 16:00 -

Supporter timezone: Europe/London (GMT+00:00)

This topic contains 2 replies, has 2 voices.

Last updated by davidS-53 6 years, 4 months ago.

Assisted by: Nigel.

Author
Posts
#1085434

I need to update post slug when post title is changed. I've got the below code so far which doesn't work- perhaps you can suggest why? Cheers.

add_action('cred_save_data', 'build_post_title', 10, 2);
	function build_post_title($post_id, $form_data) {

		// Get current title
		$title = get_the_title();
		$slug = sanitize_title($title);

		// Update the post into the database
		$my_post = array(
			'post_name' => $slug
		);
		wp_update_post( $my_post ); 

	}
#1085557

Nigel
Supporter

Languages: English (English ) Spanish (Español )

Timezone: Europe/London (GMT+00:00)

Hi David

Always helps to check the documentation first: https://codex.wordpress.org/Function_Reference/wp_update_post

>> You must include "ID", otherwise a WP_Error will be thrown.

You can also save a function call, as the title is available in the $_REQUEST object, so try the following:

add_action( 'cred_save_data', 'build_post_title', 10, 2 );
function build_post_title($post_id, $form_data) {
 
    // Get current title
    $title = $_REQUEST['post_title'];
    $slug = sanitize_title($title);
     
    // Update the post into the database
    $my_post = array(
        'ID'    => $post_id,
        'post_name' => $slug
    );
    wp_update_post( $my_post ); 
}

Note that you aren't limiting this to a particular form, it will apply to all Toolset Forms.

#1087142

Cheers, managed to sort it out from there.