Having many comments you want to get rid of can be a huge task if using the WordPress backend. With WP-CLI, it’s much faster. So here’s how to do it.

Prerequisites

Since in my case, I want to remove all comments and also disable comments for all entries, I don’t have to deal with any form of limiting the commands in any way. WordPress allows you to only handle the comment status for new posts – that means that you can’t disable comments for all of your posts globally, but only for new ones. So, you also have to loop through all posts to disable comments.

So basically, you’ll need three commands:

  • Disable comments for new posts
  • Disable comments for all existing posts
  • Delete all existing comments

Disable comments for new posts

Disabling comments for new posts can be also achieved via the backend in WordPress in a reasonable amount of time. Go to Settings > Discussion > Default post settings and disable the option “Allow people to submit comments on new posts”.

However, since we want to achieve this via WP-CLI, you can run the following command:

wp option set default_comment_status ""Code language: Bash (bash)

Disable comments for all existing posts

Since there may be existing posts with enabled comments (each post that has been created while the default comment status was set to allow comments), we have to loop through all this posts and disable comments. This could also be done via the backend in WordPress, but would also take some time, even if you can do it via Quick Edit.

This command will automate it via WP-CLI:

for post_id in $(wp post list --format=ids); do wp post update $post_id --comment_status=closed; doneCode language: Bash (bash)

Delete all existing comments

Depending on the amount of your comments, you could go to Comments in the backend, multi-select all comments and delete them. However, if you have multiple pages, this may take longer than necessary. Additionally, you’ll have to delete the comments again from the trash where they land initially after deleting them.

So, it’s time-saving to delete them via WP-CLI:

wp comment delete $(wp comment list --format=ids) --forceCode language: Bash (bash)

What this command does is first listing all comment IDs and then deleting them all with the --force flag, which means it doesn’t move them to the trash, first. You could also limit deleting comments with a specific status by adding the --status flag, e.g. if you only want to delete spam comments. This would look like this with the --status=spam flag:

wp comment delete $(wp comment list --status=spam --format=ids) --forceCode language: Bash (bash)

Conclusion

WP-CLI in general can save you much time, and especially for such tasks where you have to deal with large datasets, it makes it much more pleasant. There’s so much you can do with it and you can find out all of it in the WP-CLI documentation.

Leave a Reply

Your email address will not be published. Required fields are marked *