Bulk remove custom post type and its attachments with wp-cli?
I have a custom post type called "meetings" and I will like to bulk remove all the posts and all of its attachment images...
Can this be done with the wp-cli?
thank you!
I have a custom post type called "meetings" and I will like to bulk remove all the posts and all of its attachment images...
Can this be done with the wp-cli?
thank you!
I know you asked how to do this through wpCLI, but you could just run function to do it:
add_action( 'before_delete_post', 'delete_all_attached_media' );
function delete_all_attached_media( $post_id ) {
if( get_post_type($post_id) == "meetings" ) {
$attachments = get_attached_media( '', $post_id );
foreach ($attachments as $attachment) {
wp_delete_attachment( $attachment->ID, 'true' );
}
}
}
Add this function to your functions.php and then when you're in the backend select all your "meetings" cpts and delete. When you clear the trash, this function will fire and delete all the attachments associated with the posts being deleted.
To do this, you could use wp post list and pipe the output into wp post meta delete using xargs
.
Here's an example command to delete the featured images in the meetings
post type:
wp post list --post_type= meetings --fields=ID --format=csv | xargs -I % wp post meta delete % _thumbnail_id
You can use wp post meta list on a post to get the names of the fields you wish to delete and modify the command above accordingly.
Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.