运行 仅对自定义 post 类型数组起作用

Run function on custom post type array only

我想 运行 仅在给定的自定义 post 类型上遵循代码。现在它 运行 仅适用于一种特定的自定义类型 'file' .

我尝试将函数添加到数组中,但我很确定这不对

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

}

例如,仅当自定义 post 类型为 'file' 或 'share' 或 'folder' 时,特色图片将在删除 post 时被删除.

您可以使用 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