Skip to content

Instantly share code, notes, and snippets.

@itzikbenh
Last active January 9, 2020 20:35
Show Gist options
  • Save itzikbenh/3d3b71b4f92274dfb6962d70c93c666f to your computer and use it in GitHub Desktop.
Save itzikbenh/3d3b71b4f92274dfb6962d70c93c666f to your computer and use it in GitHub Desktop.
guide
<button class="delete-post" id="<?php echo $post->ID ?>" type="button" name="button">
Delete Post
</button>
(function($) {
$(".delete-post").on("click", function() {
var post_id = this.id;
console.log("post id is ", post_id);
$.ajax({
url: theme_data.site_url + 'wp-json/delete-post/v1/post',
method: 'POST',
beforeSend: function(xhr) {
xhr.setRequestHeader( 'X-WP-Nonce', theme_data.nonce );
},
data: {
post_id: post_id
}
}).done(function(data){
console.log("data is: ", data);
}).fail(function(data){
console.log("errors are: ", data);
});
})
})(jQuery);
//Make sure to include this file in your functions.php file.
//Something like - include( get_template_directory() . '/path/delete-post.php' );
function delete_post(WP_REST_Request $request)
{
$post_id = $request['post_id'];
if(wp_delete_post( $post_id, false ))
{
return "Post has been deleted successfully";
}
else
{
return "Something went wrong";
}
}
//Endpoint for adding event
//Add this to your enqueue script function.
wp_localize_script( 'theme_js', 'theme_data', array('nonce' => wp_create_nonce( 'wp_rest' ), 'site_url' => network_site_url( '/' )) );
function water_endpoints()
{
register_rest_route('delete-post/v1', '/post/', array(
'methods' => 'POST',
'callback' => 'delete_post'
));
}
add_action( 'rest_api_init', 'water_endpoints' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment