Disable and delete comments entirely with WP-CLI
Published: â Leave a comment
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; done
Code 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) --force
Code 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) --force
Code 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.