To create a post in WordPress using wp_insert_post()
and set the post’s slug equal to its ID, you need to follow these steps:
- Insert the post using
wp_insert_post()
. - Once the post is created, retrieve its ID.
- Update the slug of the post using
wp_update_post()
.
Here is an example code:
// 1. Create the post
$post_data = array(
'post_title' => 'Post Title',
'post_content' => 'Post content',
'post_status' => 'publish', // or 'draft' depending on your needs
'post_type' => 'post', // post type, can be 'page' or other if needed
);
$post_id = wp_insert_post($post_data);
// 2. Update the slug, setting it equal to the post ID
if ($post_id) {
$post_slug = $post_id; // Set slug equal to ID
$post_data = array(
'ID' => $post_id,
'post_name' => $post_slug, // This is the slug
);
wp_update_post($post_data);
}
Explanation:
- First, we create the post using
wp_insert_post()
by passing data such as the title and content. - After successfully creating the post, we retrieve its ID and update the post using
wp_update_post()
, setting the slug equal to the ID.
This way, the slug will automatically match the post’s ID.