HowTo – WordPress Adding A Delete Post Link To Your Pages

Filed under: Wordpress Tips

wordpress-logoIf you run a large or busy website there are times when you will need to delete old or bad posts from your site. This means jumping back and forth between your Dashboard and the FrontEnd of your site while you are hunting down posts to get rid of.

Although many or most themes will provide an edit link when you are viewing a single page or post this still means heading into your backend to make the delete of the page.

The solution is to add a Delete Post link next to the Edit Post link.

To make use of the Delete Post link you need to be logged into WordPress and with the use of a conditional statement we can display the delete post link only to those users that have the rights to delete posts.

The following code will display a Delete Post link when placed inside your Loop.

[php]
<?php if ( current_user_can(‘delete_post’, get_the_id() ) ) : ?>
<a href="<?php echo get_delete_post_link( get_the_id() ); ?>" >DELETE THIS POST</a>
<?php endif; ?>

[/php]

Because the above code works when it is inside the Loop you can place this link inside your single.php page.php or within your category  pages loop.

This will allow a logged in administrator to browse through their categories and delete pages quickly without the need to view the post or head into the backend.

With the use of other conditional statements you can display the_content to administrators and excerpts on category pages to your visitors.

How creative you get is up to you.

If you do not use the conditional statement as shown above

current_user_can('delete_post'

Then your visitors will be shown a # link to the same location that they are currently at…
meaning if you use this in your single.php they will have a link back to the same page if you use it in a category page they will link back to the same place.

Double check by logging out of your WordPress site and checking the URL generated but it is better just to hide this option for anyone that is not logged in and also able to delete posts.

Options when using get_delete_post_link

By default the link will put the post in your trash which is not a bad idea but you can force a true delete by using the following.

Use this with care because there is no going back as you know.

$force_delete = true

[php]
<?php if ( current_user_can(‘delete_post’, get_the_id() ) ) : ?>
<a href="<?php echo get_delete_post_link( get_the_id(),$force_delete=true ); ?>" >DELETE THIS POST</a>
<?php endif; ?>

[/php]

Now get out there and start cleaning up your sites.