I have a link-button on my website to delete a user's "Item". This item translates into an entry in one table, a full separate table, and a WP post.
I'm using SweetAlert to get confirmation from the user to delete their item. This confirmation sends an AJAX request to an external PHP file to remove the table entry, drop the table, and delete the WP post, all without refreshing the page.
My code from the external PHP file works flawlessly when I paste it into a page on my site and post the variables to it, but when I send the values through an AJAX request it fails when it comes to delete the WP Post (using wp_delete_post()) and the only error I can see in the browser's developer tools is a 500 internal error.
Here's my code in question.
HTML
<span id="userId" hidden><?php echo $user_id; ?></span>
<span id="Name" hidden><?php echo $name; ?></span>
<span id="blogId" hidden><?php echo $blog_id; ?></span>
<a id="delete" class="btn-cancel" href="">Delete</a>
JQuery /var/www/html/wp-content/themes/custom/js/my.js
(function($){
$('document').ready(function(){
$('#delete').click(function(event){
event.preventDefault();
swal ({
icon: "warning",
title: "Confirm Delete Request",
text: "Are you sure you want to delete '" + $('#Name').html() + "'?
This action is not reversible and all associated data will be lost!",
closeOnEsc: false,
closeOnClickOutside: false,
showCloseButton: false,
buttons: {
cancel: {
text: "NO, Get me Out",
value: false,
visible: true,
},
confirm: {
text: "YES, Delete! ME",
value: true,
visible: true,
}
},
})
.then(function(value) {
if (value == true){
var data = 'name=' + $('#Name').html() + '&user_id=' + $('#userId').html() + '&blog_id=' + $('#blogId').html();
$.ajax({
type: 'POST',
url: '../wp-content/themes/onepress-child/includes/delete.php',
data: data,
dataType: 'json',
success: function(r) {
if (r=="2") {
alert('Deleted');
} else if (r=="1") {
alert('Not an Admin');
} else if (r=="0") {
alert('Bad Name');
} else {
alert('Error');
}
}
});
} else {
window.history.back();
}
});
});
PHP /var/www/html/wp-content/themes/custom/includes/delete.php
(I've left the MySQL code out because I don't have a problem with that
include_once "../../../../wp-includes/post.php"
if (wp_delete_post($blog_id, true)){
echo "2"; //Success
}
Does anyone know why the wp_delete_post() function is failing? The 500 Internal Error does not give me any information for troubleshooting purposes.
I tried including the source file as described in the WP Codex (include_once "wp-includes/post.php";) but that is not the issue.