Skip to content

Instantly share code, notes, and snippets.

@jazibsawar
Created October 2, 2017 12:28
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save jazibsawar/a8c94a7361b47f507a23c2620e69b3c3 to your computer and use it in GitHub Desktop.
Save jazibsawar/a8c94a7361b47f507a23c2620e69b3c3 to your computer and use it in GitHub Desktop.
WordPress $wpdb: Delete all posts of a custom post type with its associated meta data (taxonomies, post meta) using SQL query & $wpdb
<?php
function delete_custom_posts($post_type = 'post'){
global $wpdb;
$result = $wpdb->query(
$wpdb->prepare("
DELETE posts,pt,pm
FROM wp_posts posts
LEFT JOIN wp_term_relationships pt ON pt.object_id = posts.ID
LEFT JOIN wp_postmeta pm ON pm.post_id = posts.ID
WHERE posts.post_type = %s
",
$post_type
)
);
return $result!==false;
}
?>
@LorincJuraj
Copy link

Don't forget to use $wpdb->prefix instead of wp_ for case when WP uses non-default database prefix.

@thebigtine
Copy link

life saver

@angryalbatross
Copy link

Hero. Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment