This is how I ended up solving this issue. Originally I used this code for the link to delete an individual post:
<?php if( !(get_post_status() == 'trash') ) : ?>
<a class="delete-post" onclick="return confirm('Are you sure you wish to delete post: <?php echo get_the_title() ?>?')"href="https://wordpress.stackexchange.com/questions/78144/<?php echo get_delete_post_link( get_the_ID() ); ?>">Delete</a>
<?php endif; ?>
After checking to see if the user was logged in and if the user was the author of this post. This didn’t work as mentioned in my original post.
Instead I used a simple delete button (with the same checks as mentioned above):
<form class="delete-post" action="<?php bloginfo('url'); ?>/edit-post" method="post">
<input id="post_id" type="hidden" name="postid" value="<?php the_ID(); ?>" />
<input type="submit" value="Delete" />
</form>
and this jQuery script to make an ajax call that will run my php script:
jQuery(document).ready(function($){
$('.delete-post').bind('click', function(e){
e.preventDefault();
var post_id;
post_id = $("#post_id").val();
var data = {};
var obj = {data: data};
data['post_id'] = post_id;
alert('Are you sure you wish to delete this post?');
process_delete_post();
function process_delete_post() {
jQuery.ajax({
type: "POST",
url: run_delete_post.ajaxurl,
data: ({
post_id : data['post_id'],
action : 'run_delete_post_script',
}),
success: function() {
location.href = "";
},
error: function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connect.\n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
}
});
});
In my functions.php file, I set up my ajax call:
function mytheme_delete_post() {
if ( is_page_template( 'edit-delete-posts.php' ) ) {
wp_enqueue_script( 'process-delete-post', get_template_directory_uri().'/js/process-delete-post.js', array('jquery'), true);
wp_localize_script( 'process-delete-post', 'run_delete_post', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
}
add_action('template_redirect', 'mytheme_delete_post');
$dirName = dirname(__FILE__);
$baseName = basename(realpath($dirName));
require_once ("$dirName/functions_custom.php");
add_action("wp_ajax_run_delete_post_script", "run_delete_post_script");
And then, the actual php script to delete the post in my functions_custom.php file:
function run_delete_post_script() {
// Test for current user
mytheme_get_current_user();
//Get the data from the submit page and convert to php variables
foreach ($_POST as $field => $value) {
if (isset($_POST[$field])) {
$$field = $value;
}
}
wp_delete_post( $post_id );
}