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

2 Answers
2

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…

On line 3203 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:

   $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.

Leave a Reply

Your email address will not be published. Required fields are marked *