WordPressの管理画面でユーザーを削除する際、削除ユーザーが所有するコンテンツを すべてのコンテンツを消去するか、他のユーザーへ移すかどうか聞いてきますので 必要ならばその際に移す先のユーザーを選択してユーザー削除します。
「すべてのコンテンツを消去します」を選択した場合 投稿や固定ページのデータはごみ箱に入りますが、画像やカスタム投稿(物件や商品等)のデータは完全に削除されます。
それをよく確認しないでユーザー削除してしまう管理者がいるようで、何もしてないのに投稿や画像がいつのまにか消えた と たまに 言われる事があります。
そこで ユーザーを削除する際、警告ダイアログを表示するか、削除ユーザーの持っているコンテンツの所有者をユーザー削除前に強制的に変更するTipsを紹介します。
コード
以下のどちらかのコードを my-plugin.php に張り付けてみてください。
ユーザーを削除する際、警告ダイアログを表示する。
削除するユーザーが何らかのコンテンツ(投稿や画像)を所有していて 「すべてのコンテンツを消去します」を選択 して「削除を実行」ボタンを押した時に警告ダイアログを表示します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | /** * ユーザーを削除する際、警告ダイアログを表示する。 * * Fires at the end of the delete users form prior to the confirm button. * * @since 4.5.0 * do_action( 'delete_user_form', $current_user, $userids ); * * @param WP_User $current_user WP_User object for the current user. * @param array $userids Array of IDs for users being deleted. * License: GPLv2 or later */ function nendebcom_delete_user_confirm() { ?> <script type= "text/javascript" > jQuery(document).ready( function () { $( '#submit' ).on( 'click' , function (event) { if ( $( "#delete_option0" ).val() == "delete" && $( "input[name=delete_option]:checked" ).val() === "delete" ){ if ( window.confirm( '削除するユーザーの 所有しているすべての投稿、物件、画像を削除します。\n「OK」を押すと元には戻せません。\n\n中止するには「キャンセル」を、すべて削除していい場合は「OK」をクリックしてください。' )){ return true; } else { return false; } } }); }); </script> <?php } add_action( 'delete_user_form' , 'nendebcom_delete_user_confirm' ); |
ユーザーを削除する際、削除ユーザーのコンテンツの所有者を強制変更する。
いっその事、無条件でコンテンツの所有者を変更して削除させないようにします。
削除対象のユーザーが コンテンツを持っているのに「すべてのコンテンツを消去します」を選択して 「削除を実行」してしまった時に動作します。
この場合は ユーザー削除をしている管理者に所有者は変わります。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | /** * ユーザーを削除する際、削除ユーザーのコンテンツの所有者を強制変更する * * @wp_delete_user * * do_action( 'delete_user', $id, $reassign ); * @param int $id ID of the user to delete. * @param int|null $reassign ID of the user to reassign posts and links to. * Default null, for no reassignment. * License: GPLv2 or later */ function nendebcom_delete_user_content2admin( $id , $reassign ) { global $wpdb ; global $user_ID ; //現在のユーザーIDを取得 if ( null === $reassign ) { $reassign = $user_ID ; //所有変更先のユーザーID // for posts $post_ids = $wpdb ->get_col( $wpdb ->prepare( "SELECT ID FROM $wpdb->posts WHERE post_author = %d" , $id ) ); $wpdb ->update( $wpdb ->posts, array ( 'post_author' => $reassign ), array ( 'post_author' => $id ) ); if ( ! empty ( $post_ids ) ) { foreach ( $post_ids as $post_id ) clean_post_cache( $post_id ); } } } add_action( 'delete_user' , 'nendebcom_delete_user_content2admin' , 10, 2 ); |
変更先のユーザーを固定したい場合は $user_IDを 実数値(変更先のユーザーID) にしてください。
参考
delete_user_form | Hook | WordPress Developer Resources
https://developer.wordpress.org/reference/hooks/delete_user_form/
delete_user | Hook | WordPress Developer Resources
https://developer.wordpress.org/reference/hooks/delete_user/