In a recent project, I was working with someone who wanted to mark a comment as unapproved regardless of the value that was set in the WordPress settings.

Specifically, the person was using a plugin that allowed for certain attachments to the plugin. In order to make sure that the comment could be screened prior to allowing it to go public on the blog, they wanted to moderate it from the dashboard without needed to completely enable comment moderation across the board.

This is something that’s relatively easy to achieve programmatically.

How To Mark a Comment as Unapproved

First, you need to register an action with the `wp_insert_comment` action.

For example:

add_filter( 'wp_insert_comment', 'example_save_comment' );

Next, you’ll need to define the `example_save_comment` function. Note that this function will receive the comment ID as a parameter whenever the action is called.

As such, the function should look like this:

function example_save_comment( $comment_id ) {
    // ...
}

After that, it’s a matter of performing the following steps:

  1. Retrieve the comment either as an object or as an array. I’ll be using an object.
  2. Set the `comment_approved` flag to 0 (which is used to indicate that it’s not approved).
  3. Use the `wp_update_comment` WordPress API function to update the comment.

The final version of the function should look like this:

function example_save_comment( $comment_id ) {

    // Get the comment based on the incoming ID
    $comment = get_comment( $comment_id );

    // Set its approved comment to 0
    $comment->comment_approved = 0;

    // Save this value to the database
    wp_update_comment( $comment );

}

In the code above, this will actually markĀ every comment as unapproved, so you’ll obviously want to use some type of conditional if you’re looking to only markĀ some of the comments are unapproved.

But that’s easy enough – just wrap the code in the hook in whatever conditional that’s necessary.

But There’s a Gotcha

The main problem with doing something like this is that it may cause a disjunction between what the user expects to happen and what really happens.

Case in point: Assume that the user as their WordPress settings configured in such a way that once a comment is approved by a single author, then their future comments should always be approved.

With the code above, that’s not the case.

Arguably, the best way to handle this is to introduce a settings page that gives the user the option to mark a comment (or a specific type of comment, depending on how complicated your work is) as unapproved based on a certain condition.

Though that level of detail is beyond the scope of what I’m trying to show here, it’s still an important consideration if you’re going to be introducing this into a project.