カスタム投稿は、開発途中にやっぱりそれいらない。
となることも少なくありません。
とはいえ、開発環境ではほとんど問題にならないので、データの残りカスがでても気にしないのですが。。
でも、カスタム投稿を含んだプラグインを提供するとなると話は別です。
プラグインで用意したカスタム投稿に投稿した後に、そのプラグインをアンインストールしたら、投稿した内容も削除しないといけない場合があります。
そこで。
WordPressで、カスタム投稿に投稿済みの内容がある場合に、その内容を削除する方法です。
function delete_posts($postType=null) {
if (!$postType) {return null;}
global $wpdb;
$tn_posts = $wpdb->prefix . 'posts';
$tn_postmeta = $wpdb->prefix . 'postmeta';
$select = "DELETE FROM $tn_posts " ;
$select .= "WHERE post_type='$postType' ;";
$results = $wpdb->query( $select );
return $results;
}
function delete_postmeta($postType=null) {
if (!$postType) {return null;}
global $wpdb;
$tn_posts = $wpdb->prefix . 'posts';
$tn_postmeta = $wpdb->prefix . 'postmeta';
$select = "DELETE pm FROM $tn_postmeta pm ";
$select .= "LEFT JOIN $tn_posts p ON p.ID=pm.post_id ";
$select .= "WHERE p.post_type='$postType' ;";
$results = $wpdb->query( $select );
return $results;
}
delete_postmeta('my_posttype');
delete_posts('my_posttype');
delete_postmeta()でカスタムフィールドを削除してから、 delete_posts()でカスタム投稿の投稿データを削除しています。
my_posttypeにはカスタム投稿のpost typeを入れるわけです。