Get the post_id of a new post

There are several ways to get the id of a post after it has been saved (auto, etc.), but is there a way to get the post id immediately after you create a new post?

I am trying to create a directory using the post id, but I cannot seem to get a static post id.

the code below seems to work but I get an auto incremented id back every time the new post auto saves the draft, I continually get a new number.

function myfunction( $id ) {
        if (!file_exists("/www/foo/blog/wp-content/uploads/" . $id)) {
            mkdir("/www/foo/blog/wp-content/uploads/" . $id, 0777);
        }
}
add_action('save_post', 'myfunction');

I would like to get the post id that it will be saved as. Surely WP has a method for determining this correct? Or does the draft auto save every minute incrementing the id by one until the actual ‘publish’ button is clicked?

thoughts?

cheers!
bo

1 Answer
1

Try this…

add_action('post_updated', 'myfunction');

function myfunction( $post_id ) {

    global $post;

        if (!file_exists("/www/foo/blog/wp-content/uploads/" . $post_id)) {
            mkdir("/www/foo/blog/wp-content/uploads/" . $post_id, 0777);
        }
}

NOTE: Change from save_posts to post_updated which will stop the duplicate issue as it fires on “publish” only and not every time you hit add new or update etc.

NOTE: I verified this for you by testing the snippet above – all good.

NOTE: You can also use (wp_upload_dir() . $post_id, 0777) if you want a path that is more transportable or if you are developing a plugin or theme for public use.

Leave a Comment