How to use wp_insert_post() to create a post whose post slug is equal to its ID

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:

  1. Insert the post using wp_insert_post().
  2. Once the post is created, retrieve its ID.
  3. 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.

How useful is the publication?

Click on a star to rate it!

Average score 5 / 5. Number of grades: 1

No ratings yet. Rate it first.

Similar posts

How to transfer a site from dle to WordPress?

Transferring a website from DLE (DataLife Engine) to WordPress can be a complex process, especially if the site has a lot of content. Here’s a step-by-step guide: 1. Preparation 2. Export Data from DLE DLE uses its own database structure, so you’ll need to export data and convert it into a format compatible with WordPress:…
Read more