Skip to:
Content
Pages
Categories
Search
Top
Bottom

Delete post comments via front end


  • Henry
    Member

    @henrywright-1

    function custom_delete_post_comment() {
       $comment_id = comment_ID();
       wp_delete_comment( $comment_id, true ) 
    }

    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

Viewing 6 replies - 1 through 6 (of 6 total)

  • Henry
    Member

    @henrywright-1

    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>

    Henry
    Member

    @henrywright-1

    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.


    Henry
    Member

    @henrywright-1

    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;


    @mercime
    Moderator

    @mercime


    Henry
    Member

    @henrywright-1

    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.


    @mercime
    Moderator

    @mercime

    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 🙂

Viewing 6 replies - 1 through 6 (of 6 total)
  • The topic ‘Delete post comments via front end’ is closed to new replies.
Skip to toolbar