我只想在给定的自定义帖子类型上运行以下代码。现在,它仅在一种特定的自定义类型“文件”上运行。
我试图将函数添加到数组中,但我很确定这不是正确的事情
// For deleting attachments when Deleting POSTS
add_action( 'before_delete_post', 'mtp_delete_attached_thumbnail_for_trashed_product', 20, 1 );
function mtp_delete_attached_thumbnail_for_trashed_product( $post_id ) {
// gets ID of post being trashed
$post_type = get_post_type( $post_id );
// does not run on other post types
if ( $post_type != 'file' ) {
return true;
}
// get ID of featured image
$post_thumbnail_id = get_post_thumbnail_id( $post_id );
// delete featured image
wp_delete_attachment( $post_thumbnail_id, true );
}
例如,仅当自定义帖子类型为“文件”,“共享”或“文件夹”时,删除帖子时才会删除精选图片。
答案 0 :(得分:1)
您可以使用in_array()简化此过程。
// For deleting attachments when Deleting POSTS
add_action( 'before_delete_post', 'mtp_delete_attached_thumbnail_for_trashed_product', 20, 1 );
function mtp_delete_attached_thumbnail_for_trashed_product( $post_id ) {
// List of post types.
$post_types = array(
'file',
'share',
'folder',
);
// gets ID of post being trashed
$post_type = get_post_type( $post_id );
// does not run on other post types
if ( ! in_array( $post_type, $post_types, true) ) {
return true;
}
// get ID of featured image
$post_thumbnail_id = get_post_thumbnail_id( $post_id );
// delete featured image
wp_delete_attachment( $post_thumbnail_id, true );
}