OK my code so far which partially works. I just need the page to reload or refresh to reflect that the comment has been deleted from the database. Any ideas?
if ( isset( $_POST['comment_delete_nonce'] ) ) {
if( wp_verify_nonce( $_POST['comment_remove_nonce'], 'comment-remove-nonce' ) ) {
set_query_var( 'commentid1', $_POST['commentid'] );
wp_delete_comment( get_query_var( 'commentid1'), true );
}
}
HTML form:
<form method="POST" action="" class="delete-comment-form">
<input type="hidden" name="comment_remove_nonce" value="<?php echo wp_create_nonce('comment-remove-nonce'); ?>" />
<input type="hidden" name="commentid" value="<?php comment_ID() ?>" />
<input type="submit" value="Delete" title="Delete" id="submit-btn" class="btn" />
</form>
Got it! I had to turn my form processing code into a function and hook it to the wp_loaded action. This avoided getting the dreaded “headers already sent” error.
Just to add (if anyone is interested), to have the page reload i’m using this as the last line in my function wp_safe_redirect( wp_get_referer() ); exit;
Thanks @mercime – wish you told me about that plugin yesterday. Spent about 5 hours getting my code to work – the problem was all down to the “headers already sent”. You have to redirect early on (around the wp_loaded action) – before the headers are sent or you’ll hit problems like I did.
Sorry, wasn’t “in” totally yesterday. Glad you resolved the issue on your own … as well as learned more about WP comments in the process 🙂
Henry
@henrywright-1
11 years, 2 months ago
I have been able to write this function which will delete a comment with a given ID.
Now, I’d like blog authors to be able to delete post comments via the front end. (this will avoid them having to go into WP dashboard and delete comments in the standard way).
I am thinking the best approach will be to have a delete button in the comments loop next to each comment.
Anyone have some pointers how to have the delete button make use of the delete function? I’m not very experienced in writing forms so hoping someone can help