問題描述
我有一個自定義帖子類型的概述。這些都有定製税和附件。
在我的概述中,我需要提供刪除條目的鏈接。因此,我還需要刪除附件和元數據。
我在用這個:
if ( !current_user_can( 'delete_bkroadkill', $post->ID ) )
return;
$link = "<a href='" . wp_nonce_url( get_bloginfo('url') . "/wp-admin/post.php?action=delete&post=" . $post->ID, 'delete-post_' . $post->ID) . "'>".$link."</a>";
echo $before . $link . $after;
我發現 Delete Post Link to delete post, its meta and attachments,但沒有提供任何解決方案。
哪些不會刪除除帖子以外的其他內容。這樣做的正確方法是什麼?
最佳解決方案
@s_ha_dum 建議 Post meta 將被自動刪除。因此,因為他的聲譽表明他知道他在説什麼,這個解決方案只能處理 Post 附件。
我建議檢查 before_delete_post()鈎子的文檔,因為可以查看要刪除的帖子類型等等。
add_action('before_delete_post', 'delete_post_attachments');
function delete_post_attachments($post_id){
global $post_type;
if($post_type !== 'my_custom_post_type') return;
global $wpdb;
$args = array(
'post_type' => 'attachment',
'post_status' => 'any',
'posts_per_page' => -1,
'post_parent' => $post_id
);
$attachments = new WP_Query($args);
$attachment_ids = array();
if($attachments->have_posts()) : while($attachments->have_posts()) : $attachments->the_post();
$attachment_ids[] = get_the_id();
endwhile;
endif;
wp_reset_postdata();
if(!empty($attachment_ids)) :
$delete_attachments_query = $wpdb->prepare('DELETE FROM %1$s WHERE %1$s.ID IN (%2$s)', $wpdb->posts, join(',', $attachment_ids));
$wpdb->query($delete_attachments_query);
endif;
}
上述文件的一個重要注意事項 –
重要的是要注意,只有當 WordPress 用户清空垃圾箱時,掛鈎才會運行。如果您使用此掛鈎註釋,如果用户正在刪除附件,則不會觸發,因為附件被強制刪除,即不會發送到廢紙簍。而是使用 delete_post()鈎子。
另一個註釋
我應該提到,雖然此答案中的代碼將刪除與 Post 附件相關的數據庫中的所有行,但實際上它們實際上不會刪除附件。
我的理由是表現。根據您擁有的附件數量,一次刪除它們可能需要一段時間。我建議最好只刪除所有附件的數據庫條目,以增強用户體驗,然後在另一個時間運行一些單獨的房屋刪除實際附件 (搜索和刪除 non-associated 文件是很容易的) 。基本上,在用户體驗期間,較少的查詢+更少的工作=更少的時間。
次佳解決方案
我用這個來刪除相關的媒體。如果您想要針對某個帖子類型進行測試,則可以包含 global $post_type 變量。幾乎所有的附件都會被逐一刪除。 Reference
function delete_associated_media( $id ) {
$media = get_children( array(
'post_parent' => $id,
'post_type' => 'attachment'
) );
if( empty( $media ) ) {
return;
}
foreach( $media as $file ) {
wp_delete_attachment( $file->ID );
}
}
add_action( 'before_delete_post', 'delete_associated_media' );
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。