Search code examples
phpwordpresswoocommerceproduct

Automatically update the slug of a product when the title of the product is updated


I want to automatically update the slug of a product when its product title is updated.

I read on some posts that wp_update_post would probably be the best option to start with.

I also tried the code below but it's not working good, it's causing too many conflicts.

Any help please?


Solution

  • You haven't provided any code in your question... and you haven't done thorough research to your problem...

    Please see:

    wp_update_post can be used to update the post slug. It is appropriate for making changes to a post's properties, including the slug.

    You can use the save_post action which triggers whenever a post or page is created or updated. It can be used to execute custom functions right after a post is saved.

    Then you can use sanitize_title to create a URL-friendly version of the post title. It ensures that characters which are not suitable for URLs are removed or replaced.

    The code below will automatically update the slug of a product, when you make updates to the product name/title:

    /* Update product slug to product title, when product is saved */
    function slug_save_post_callback( $post_ID, $post, $update ) {
        // Prevent function from running during an autosave. Can cause unnecessary updates.
        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
            return;
        }
    
        // Check if post type is product, if not, exit the function
        if ( $post->post_type != 'product' ) {
            return;
        }
    
        // Ensures that only users with the appropriate permissions can trigger the function
        if ( ! current_user_can( 'edit_post', $post_ID ) ) {
            return;
        }
    
        // Generate new slug based on the post title using sanitize_title
        $new_slug = sanitize_title( $post->post_title, $post_ID );
        // If new slug is the same as the current slug, exit the function
        if ( $new_slug == $post->post_name ) {
            return; // already set
        }
    
        // Remove save_post action to prevent infinite looping
        remove_action( 'save_post', 'slug_save_post_callback', 10, 3 );
        // Update the post slug with new slug
        wp_update_post( array(
            'ID' => $post_ID,
            'post_name' => $new_slug
        ));
        // Re-hook the save_post action to ensure the function is called again
        add_action( 'save_post', 'slug_save_post_callback', 10, 3 );
    }
    add_action( 'save_post', 'slug_save_post_callback', 10, 3 );
    

    The code should be added to your functions.php file of your active child theme. Tested and works.