Question: How can i create unique slug while inserting a new post..

I know i can query posts and compare the records to create unique slug but

I want to insert a post with unique slug at the same time.

Lets say i have post title and needed data for the post and want to insert it with wpquery
Does wordpress have a function to handle all by itself..

When i insert a post with st. like

```
$my_post = array(
  'post_title'    => 'My post',
  'post_content'  => 'This is my post.',
  'post_status'   => 'publish',
  'post_author'   => 1,
  'post_category' => array(8,39)
);

// Insert the post into the database
wp_insert_post( $my_post );

```

Doest it handle the slug automatically..

I want to insert this post and open it with php redirect after insert..

Answer: 
You don't have to think about it - WordPress will take care of this.

Let's take a look at [`wp_insert_post` source code](https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/post.php#L3094)...

On line [3203](https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/post.php#L3203) you'll find:

```
if ( empty($post_name) ) {
    if ( !in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) ) {
        $post_name = sanitize_title($post_title);
    } else {
        $post_name = '';
    }
} else {
    // On updates, we need to check to see if it's using the old, fixed sanitization context.
    $check_name = sanitize_title( $post_name, '', 'old-save' );
    if ( $update && strtolower( urlencode( $post_name ) ) == $check_name && get_post_field( 'post_name', $post_ID ) == $check_name ) {
        $post_name = $check_name;
    } else { // new post, or slug has changed.
        $post_name = sanitize_title($post_name);
    }
}

```

So if no `post_name` is set, WP will generate it from `post_title`.

And then on line [3325](https://core.trac.wordpress.org/browser/tags/4.2.2/src/wp-includes/post.php#L3325):

```
   $post_name = wp_unique_post_slug( $post_name, $post_ID, $post_status, $post_type, $post_parent );

```

So WP will take care of uniqueness of `post_name`.
WordPress will take care about unique slug. If you want to redirect to the post after it has been created, you can get the permalink using the post ID which is returned by `wp_insert_poost()` if it was successfull:

```
$my_post = array(
  'post_title'    => 'My post',
  'post_content'  => 'This is my post.',
  'post_status'   => 'publish',
  'post_author'   => 1,
  'post_category' => array(8,39)
);

// Insert the post into the database
$post_id = wp_insert_post( $my_post );

// Check there was no errors
if( $post_id && ! is_wp_error( $post_id ) ) {

    wp_redirect( get_the_permalink( $post_id ) );
    exit;

}

```