Created
July 17, 2024 12:11
-
-
Save dantetesta/559a984106511f36d26811d38c1b56a7 to your computer and use it in GitHub Desktop.
Remove Medias de um Campo Metafield Quando o Post é Removido
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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