Tuesday, October 4, 2011

How to put WordPress “Delete Post Link”..?


I recently had a client ask for a delete post link, like the WordPress edit post linktemplate tag, for the user to delete posts when browsing the front-end of the site. He also wanted a pop-up confirmation box to appear before deleting the post. I saw variations on this function in several places, but never exactly what he asked for. So here it is:
  • a link to delete (or “trash”) a post from the front-end
  • shows only if the user is logged in and has the capability to delete that post
  • shows a confirmation pop-up box
  • if confirmed, post is trashed and page is refreshed
The following goes in the theme’s functions.php file:

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;
  }
    $message = "Are you sure you want to delete
 ".get_the_title($post->ID)." ?";
    $delLink = wp_nonce_url( get_bloginfo('url') 
. "/wp-admin/post.php?action=delete&post=" .
 $post->ID, 'delete-post_' . $post->ID);
    $htmllink = "<a href='" . $delLink . "'
 onclick = \"if ( confirm('".$message."' ) )
 { execute(); return true; } return false;\"/>"
.$link."</a>";
    echo $before . $htmllink . $after;
}

Then use the following template tag wherever you want it to appear in your theme.


<?php wp_delete_post_link('(trash)', 
'<div class="post-edit">', '</div>'); ?>

No comments:

Post a Comment