Skip to content

Using WP-CLI to Delete Posts Containing a Specific Metadata Value

I was doing some maintenance on a WordPress site for a client, and for very specific reasons, I had to use non-interactive WP-CLI commands to do anything on this site.

What I wanted to do

Delete all pages that contained a custom postmeta key and value.

For the sake of this example, I wanted to delete:

  • Post Type: Only “page” types
  • Containing the “_mykey” custom meta key with the value “value1”

Solution

Verify the posts that are going to be deleted first

It’s always advisable to double check what you’re going to delete first. The “measure twice, cut once” one database management.

wp post list --meta_key="_mykey" --fields="ID" --format=ids --post_type=page --meta_value="value1"


Delete the Data

Now that you’ve confirmed what you’re going to delete is correct, you can proceed.

wp post delete $(wp post list --meta_key="_mykey" --fields="ID" --format=ids --post_type=page --meta_value="value1")

For an added measure of safety, this only moves the posts into the trash. If you wanted to permanently delete them, add the --force flag to the delete command,

wp post delete $(wp post list --meta_key="_mykey" --fields="ID" --format=ids --post_type=page --meta_value="value1") --force

Bonus

If you want to delete the posts that contain the “_mykey” meta_key, regardless of what the value is in meta_value,

wp post delete $(wp post list --meta_key="_mykey" --fields="ID" --format=ids --post_type=page) --force

One Comment

  1. @shooper @shawnhooper Thanks for sharing this! Never seen this kind of use of variables in WP CLI and I should really start thinking this way!

    Too bad the fedi version of the post loses all the formatting. Made it hard to follow compared to just having a link.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.