Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save dantetesta/559a984106511f36d26811d38c1b56a7 to your computer and use it in GitHub Desktop.
Save dantetesta/559a984106511f36d26811d38c1b56a7 to your computer and use it in GitHub Desktop.
Remove Medias de um Campo Metafield Quando o Post é Removido
<?php
// Hook para detectar a exclusão de posts
add_action('before_delete_post', 'wpscripts_handle_post_deletion');
function wpscripts_handle_post_deletion($post_id) {
global $wpdb;
// Verifica se o post tem uma imagem destacada
$thumbnail_id = get_post_thumbnail_id($post_id);
if ($thumbnail_id) {
wpscripts_delete_attachment($thumbnail_id);
}
// Verifica o meta field '_anexo'
$anexos = get_post_meta($post_id, '_anexo', true);
if ($anexos) {
$anexos_array = explode(',', $anexos);
foreach ($anexos_array as $anexo) {
$attachment_id = $wpdb->get_var(
$wpdb->prepare(
"SELECT ID FROM {$wpdb->prefix}posts WHERE guid = %s",
$anexo
)
);
if ($attachment_id) {
wpscripts_delete_attachment($attachment_id);
}
}
}
}
function wpscripts_delete_attachment($attachment_id) {
global $wpdb;
// Remove o arquivo diretamente da pasta usando funções PHP
$file_path = get_attached_file($attachment_id);
if (file_exists($file_path)) {
if (!unlink($file_path)) {
error_log("Failed to delete file: $file_path");
}
} else {
error_log("File does not exist: $file_path");
}
// Remove a entrada da mídia usando SQL
$wpdb->query(
$wpdb->prepare(
"DELETE FROM {$wpdb->posts} WHERE ID = %d",
$attachment_id
)
);
$wpdb->query(
$wpdb->prepare(
"DELETE FROM {$wpdb->postmeta} WHERE post_id = %d",
$attachment_id
)
);
$wpdb->query(
$wpdb->prepare(
"DELETE FROM {$wpdb->term_relationships} WHERE object_id = %d",
$attachment_id
)
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment