Skip to content

Instantly share code, notes, and snippets.

@zackpyle
Last active June 2, 2023 16:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zackpyle/ba3e867951970dc7d7211a6fcc8cf6ee to your computer and use it in GitHub Desktop.
Save zackpyle/ba3e867951970dc7d7211a6fcc8cf6ee to your computer and use it in GitHub Desktop.
Make a shortcode [delete-post] for users to delete a post from the frontend if they are the author of that post
<?php //ignore this line - for git formatting
function delete_post_shortcode($atts) {
$post_id = get_the_ID();
// Check if the user is logged in and is the author of the post
if (is_user_logged_in() && is_singular() && get_the_author_meta('ID') === get_current_user_id()) {
ob_start();
?>
<button type="button" id="delete-post-button">Delete</button>
<style>
#delete-post-button {
background-color: #f44336;
color: #fff;
border: none;
padding: 8px 16px;
font-size: 14px;
border-radius: 4px;
cursor: pointer;
}
</style>
<script>
// Move the post to trash when the delete button is clicked
document.getElementById('delete-post-button').addEventListener('click', function() {
var confirmDelete = confirm('Are you sure you want to delete this post?');
if (confirmDelete) {
var postID = <?php echo $post_id; ?>;
movePostToTrash(postID);
}
});
// Function to send AJAX request and move the post to trash
function movePostToTrash(postID) {
var data = new FormData();
data.append('action', 'move_post_to_trash');
data.append('post_id', postID);
data.append('nonce', '<?php echo wp_create_nonce('move_post_to_trash_action'); ?>');
fetch('<?php echo admin_url('admin-ajax.php'); ?>', {
method: 'POST',
body: data
})
.then(response => response.json())
.then(data => {
if (data.success) {
alert('The post has been moved to the trash.');
window.location.href = '<?php echo home_url(); ?>';
} else {
alert('Failed to move the post to the trash.');
console.log(data.message);
// Handle error case
}
})
.catch(error => {
alert('An error occurred while moving the post to the trash.');
console.error(error);
// Handle error case
});
}
</script>
<?php
return ob_get_clean();
}
return '';
}
add_shortcode('delete-post', 'delete_post_shortcode');
add_action('wp_ajax_move_post_to_trash', 'move_post_to_trash_action');
add_action('wp_ajax_nopriv_move_post_to_trash', 'move_post_to_trash_action');
function move_post_to_trash_action() {
if (isset($_POST['nonce']) && wp_verify_nonce($_POST['nonce'], 'move_post_to_trash_action')) {
$post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;
if (current_user_can('delete_post', $post_id)) {
wp_trash_post($post_id);
wp_send_json_success();
} else {
wp_send_json_error(array('message' => 'You do not have permission to delete this post.'));
}
} else {
wp_send_json_error(array('message' => 'Invalid request.'));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment