Last active
January 9, 2020 20:35
-
-
Save itzikbenh/3d3b71b4f92274dfb6962d70c93c666f to your computer and use it in GitHub Desktop.
guide
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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"; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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