I'm storing an uploaded attachment to a custom directory under wp-content/uploads/my-directory/
and storing its value in wp_postmeta
table. When I'm deleting the post it's not deleting the attached file from the path.
So I tried hooking onto the delete_post
hook to delete the file from its path:
<?php
/**
* Delete Custom Attachment when deleting its post.
*
* @param integer $post_id Post ID.
*
* @return void
*/
function wpse353942_delete_attachment( $post_id ) {
if ( 'my-cpt' !== get_post_type( $post_id ) ) {
return;
}
$attachment = get_post_meta( $post_id, '_attachment', true ); // get the attachment URL.
if ( ! $attachment ) {
return;
}
$upload_dir = wp_get_upload_dir();
unlink( $upload_dir['basedir'] . '/my-directory/' . basename( $attachment ) );
}
add_action( 'delete_post', 'wpse353942_delete_attachment' );
But alas, it's not deleting the file from the directory. :(
What can I do?
I'm storing an uploaded attachment to a custom directory under wp-content/uploads/my-directory/
and storing its value in wp_postmeta
table. When I'm deleting the post it's not deleting the attached file from the path.
So I tried hooking onto the delete_post
hook to delete the file from its path:
<?php
/**
* Delete Custom Attachment when deleting its post.
*
* @param integer $post_id Post ID.
*
* @return void
*/
function wpse353942_delete_attachment( $post_id ) {
if ( 'my-cpt' !== get_post_type( $post_id ) ) {
return;
}
$attachment = get_post_meta( $post_id, '_attachment', true ); // get the attachment URL.
if ( ! $attachment ) {
return;
}
$upload_dir = wp_get_upload_dir();
unlink( $upload_dir['basedir'] . '/my-directory/' . basename( $attachment ) );
}
add_action( 'delete_post', 'wpse353942_delete_attachment' );
But alas, it's not deleting the file from the directory. :(
What can I do?
Share Improve this question edited Dec 5, 2019 at 13:15 fuxia♦ 107k39 gold badges255 silver badges459 bronze badges asked Dec 5, 2019 at 5:41 Mayeenul IslamMayeenul Islam 12.9k21 gold badges85 silver badges169 bronze badges1 Answer
Reset to default 0If you see the code of wp_delete_post()
function, you can see that, the function is deleting the post's meta data just before deleting the post itself - a line above with the delete_metadata_by_mid()
.
So, in your function, when you are trying to get the attachment URL, it's already been deleted from the database, so it's getting empty and the function is returning doing nothing.
So the best approach would be to hook on to a prior one instead of delete_post
- you can use: the before_delete_post
hook with the same function, and it should work.
Just change:
add_action( 'delete_post', 'wpse353942_delete_attachment' );
into
add_action( 'before_delete_post', 'wpse353942_delete_attachment' );
Reference:
- Action Hook:
delete_post
- Developer Reference - Function:
wp_delete_post()
- Developer Reference - Function:
delete_metadata_by_mid()
- Developer Reference - Action Hook:
before_delete_post
- Developer Reference