プログラミング未経験者の備忘録

ノンプログラマーが社内SEになったのでイチからプログラミングを勉強し始めました!

WordPressで記事を削除したと同時にメディアファイルも一緒に削除する

f:id:su3se:20190609053132j:plain

WordPressでは通常、記事を削除しても使用している画像などはサーバー内に残ってしまい不要なデータ(ゴミ)が残ってしまいます。長期的にサイト運営を行っていくうえで増え続けるデータ量をいかに減らせるかは一つの課題です。

 

テーマの為の関数(function.php)に追記

add_action( 'before_delete_post', 'nxw_delete_post_attachment' );
function nxw_delete_post_attachment( $post_id ) {
$args = array(
'numberposts' => -1,
'post_parent' => $post_id,
'post_type' => 'attachment',
'post_status' => 'any',
'post_mime_type' => 'image'
);
$attachments = get_children( $args );
foreach( $attachments as $attachment ) {
wp_delete_attachment( $attachment->ID, true );
}
}