##Deleting the "Hello World" Post
Next we want to delete the "Hello World" post. You may have seen that @Rarst has shown us how to use the wp_delete_post()
function which is exactly what we need. As he explained the second parameter will fully delete the post as opposed to moving it to the trash and the first parameter is the $post->ID
.
Of course it would be nice to be able to specify the slug instead of the $post->ID
and so I decide to find a way to do that. After some spelunking I found that WordPress has an unfortunately named function called get_page_by_path()
which actually allows us to look up any post type by its slug (it is unfortunately named because you might overlook it when trying to find something that works with post types other than 'page'
.)
Since we passing get_page_by_path()
the WordPress-defined constant OBJECT
it will return to us a post in the form of an post object. For the third parameter we passed 'post'
to indicate we wanted it to lookup post types of 'post'
. Since get_page_by_path()
will return the post object we need or return null
if no post matches the slug we can check for existence and do a lookup at the same time:
$post = get_page_by_path('hello-world',OBJECT,'post');
if ($post)
wp_delete_post($post->ID,true);
Note: We could have run code to delete every post in the database but if we had we would not be able to run this code again once we've added the posts we want to keep and that was one of our design constraints.