仅在自定义帖子类型数组上运行函数

问题描述 投票:0回答:1

我想仅在给定的自定义帖子类型上运行以下代码。现在它只在一个特定的自定义类型'文件'上运行。

我试图在一个数组中添加该函数,但我很安静,确定它不是正确的

 // 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 );

}

例如,仅当自定义帖子类型为“文件”或“共享”或“文件夹”时,删除帖子时才会删除特色图片。

php wordpress function hook custom-post-type
1个回答
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 );

}

https://www.w3schools.com/php/func_array_in_array.asp

© www.soinside.com 2019 - 2024. All rights reserved.