Another way to handle ajax requests to delete a post is to use jquery and the built-in ajax functions provided by WP.
Html
<a class="delete-post" data-postid="<?php echo get_the_id(); ?>" href="#">Delete</a>
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<script>
jQuery(document).ready(function($) {
$('.delete-post').on('click', function(e) {
e.preventDefault();
var postId = $(this).data('postid');
// Send an AJAX request to delete the post
$.ajax({
type: 'POST',
url: ajax_object.ajaxurl,
data: {
action: 'delete_post',
post_id: postId,
},
success: function(response) {
// Redirect to the profile page after successful deletion
window.location.href = '<?php echo bp_loggedinuser_link(); ?>articles/';
},
error: function(error) {
console.log(error.responseText);
}
});
});
});
</script>
functions.php
Enqueue the script.
function enqueue_custom_scripts() {
// Enqueue jQuery
wp_enqueue_script('jquery');
// Enqueue your custom script
wp_enqueue_script('custom-script', get_template_directory_uri() . '/js/custom-script.js', array('jquery'), null, true);
// Localize the script with the necessary data
wp_localize_script('custom-script', 'ajax_object', array('ajaxurl' => admin_url('admin-ajax.php')));
}
add_action('wp_enqueue_scripts', 'enqueue_custom_scripts');
function delete_post_callback() {
if (isset($_POST['action']) && $_POST['action'] == 'delete_post') {
$post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;
// Check if the user has permission to delete the post
if (current_user_can('delete_post', $post_id)) {
wp_delete_post($post_id);
echo 'Post deleted successfully';
} else {
echo 'Permission denied';
}
}
die();
}
add_action('wp_ajax_delete_post', 'delete_post_callback');
add_action('wp_ajax_nopriv_delete_post', 'delete_post_callback'); // Allow non-logged in users to delete posts