• Resolved Cezar Ayran

    (@ayrancd)


    When you create a post using wp_insert_post you don’t have to set the slug/permalink since it gets automatically based on the title, what about when you update the same post using wp_update_post? How do we update the slug again based on the post title?

Viewing 3 replies - 1 through 3 (of 3 total)
  • threadi

    (@threadi)

    If you set this as an attribute, WordPress will create a new slug for the post based on the current title:

    'post_name' => ''

    See: https://wordpress.stackexchange.com/questions/105926/rewriting-post-slug-before-post-save

    Thread Starter Cezar Ayran

    (@ayrancd)

    @threadi just tried the following code and the slug is not being updated at all

    wp_update_post(array('ID' => $id, 'post_name' => sanitize_title($_POST["product_title"])));

    I also tried it empty and no changes.

    • This reply was modified 12 months ago by Cezar Ayran.
    Thread Starter Cezar Ayran

    (@ayrancd)

    Just found a solution:

    function slug_save_post_callback( $post_ID, $post, $update ) {
        if ($post->post_type != 'product')
            return;
    
        $new_slug = sanitize_title( $post->post_title, $post_ID );
        if ($new_slug == $post->post_name)
            return; // already set
    
        // unhook this function to prevent infinite looping
        remove_action( 'save_post', 'slug_save_post_callback', 10, 3 );
        // update the post slug (WP handles unique post slug)
        wp_update_post( array(
            'ID' => $post_ID,
            'post_name' => $new_slug
        ));
        // re-hook this function
        add_action( 'save_post', 'slug_save_post_callback', 10, 3 );
    }
    add_action( 'save_post', 'slug_save_post_callback', 10, 3 );
Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Update post/slug’ is closed to new replies.