How to Add a Delete Post Link to Your WordPress Posts

How to Add a Delete Post Link to Your WordPress Posts


Some sites, especially those that allow contributors to post, may need an easy way to delete posts from time to time.

In order to make it as easy as possible, of course, the best thing to do would be to put a “Delete” button right on the post itself. Of course this delete link should only be viewable by logged in users with a certain permission level, much like an “Edit” button that many themes use.

Here’s how you can go about doing that.

First, place the following code in you functions file after the opening <php tag. (Appearance > Editor > Theme Functions – functions.php)

function wp_delete_post_link($link = 'Delete This', $before = '', $after = '')
{
global $post;
if ( $post->post_type == 'page' ) {
if ( !current_user_can( 'edit_page', $post->ID ) )
return;
} else {
if ( !current_user_can( 'edit_post', $post->ID ) )
return;
}
$link = "<a href='" . wp_nonce_url( get_bloginfo('url') . "/wp-admin/post.php?action=delete&amp;post=" . $post->ID, 'delete-post_' . $post->ID) . "'>".$link."</a>";
echo $before . $link . $after;
}

FREE EBOOK
Your step-by-step roadmap to a profitable web dev business. From landing more clients to scaling like crazy.

By downloading this ebook I consent to occasionally receive emails from WPMU DEV.
We keep your email 100% private and do not spam.

FREE EBOOK
Plan, build, and launch your next WP site without a hitch. Our checklist makes the process easy and repeatable.

By downloading this ebook I consent to occasionally receive emails from WPMU DEV.
We keep your email 100% private and do not spam.

 

Next, you will need to put some code in your theme files where you would like your delete link to show up.

I put the following code in my single.php code just above where the content of the post starts. (Appearance > Editor > Single Post – single.php)

<?php wp_delete_post_link('Delete This', '<p>', '</p>'); ?>

 

The '<p>', '</p>' in the code gives it space above it and below, but if you don’t want that space, then you can take it out:

 

<?php wp_delete_post_link('Delete This'); ?>

 

You could also put this on your Main Index Template, for example, if you wanted the link to show up on the home page too. (Appearance > Editor > Main Index Template – index.php)

And here’s what it looks like.

 

Thanks to web-templates.nu for the code.

Photo: Delete sticker icon. Vector illustration. From BigStock