Skip Navigation

[Gelöst] Update slug when post title is updated

Dieser Thread wurde gelöst. Hier ist eine Beschreibung des Problems und der Lösung.

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 vor 6 Jahren, 3 Monaten. 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.

Heute stehen keine Supporter zur Arbeit im Werkzeugsatz-Forum zur Verfügung. Sie können gern Tickets erstellen, die wir bearbeiten werden, sobald wir online sind. Vielen Dank für Ihr Verständnis.

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)

Dieses Thema enthält 2 Antworten, hat 2 Stimmen.

Zuletzt aktualisiert von davidS-53 vor 6 Jahren, 3 Monaten.

Assistiert von: Nigel.

Author
Artikel
#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

Sprachen: Englisch (English ) Spanisch (Español )

Zeitzone: 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.