Skip Navigation

[Résolu] Update slug when post title is updated

Ce fil est résolu. Voici une description du problème et la solution proposée.

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 Il y a 5 années et 8 mois. 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.

No supporters are available to work today on Toolset forum. Feel free to create tickets and we will handle it as soon as we are online. Thank you for your understanding.

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+01:00)

This topic contains 2 réponses, has 2 voix.

Last updated by davidS-53 Il y a 5 années et 8 mois.

Assisted by: Nigel.

Auteur
Publications
#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: Anglais (English ) Espagnol (Español )

Timezone: Europe/London (GMT+01: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.

This ticket is now closed. If you're a WPML client and need related help, please open a new support ticket.