覆盖wp_DELETE_POST并移至垃圾桶,而不是自定义帖子类型

时间:2020-02-08 作者:wharfdale

函数wp\\u delete\\u post()在自定义帖子类型上使用时将永久删除。这个force 标志仅适用于PAGEPOST cpt。

请参阅此帖子,了解如何使用force标志:wp_delete_post() deletes post instead of moving it to trash

问题:A plugin I have is using this function, and I want to try hook in to wp_delete_post and move the item to trash instead of permanently deleting.

是否可以使用before_delete_post 尝试在垃圾箱达到永久删除阶段之前将其移动到垃圾箱?

Alternative:根本不删除该项目。在我的情况下,我很乐意更新post状态或一些元密钥,然后我将在稍后的日期使用该元密钥对这些产品进行永久删除。

到目前为止,我的尝试-此测试只是想看看是否可以阻止运行完整的wp\\u post\\u delete。这不起作用,帖子仍然被永久删除。

function delete_handler($postid){
  return false;
}
add_action(\'before_delete_post\', __NAMESPACE__.\'\\\\delete_handler\');

1 个回复
最合适的回答,由SO网友:Antti Koskinen 整理而成

在…内wp_delete_post() 有以下代码,

/**
 * Filters whether a post deletion should take place.
 *
 * @since 4.4.0
 *
 * @param bool|null $delete       Whether to go forward with deletion.
 * @param WP_Post   $post         Post object.
 * @param bool      $force_delete Whether to bypass the trash.
 */
$check = apply_filters( \'pre_delete_post\', null, $post, $force_delete );
if ( null !== $check ) {
    return $check;
}
因此,我认为通过以下过滤,您可能可以防止删除。

function prevent_cpt_delete( $delete, $post, $force_delete ) {
  // Is it my post type someone is trying to delete?
  if ( \'my_post_type\' === $post->post_type && ! $force_delete ) {
    // Try to trash the cpt instead
    return wp_trash_post( $post->ID ); // returns (WP_Post|false|null) Post data on success, false or null on failure.
  }
  return $delete;  
}
add_filter(\'pre_delete_post\', \'prevent_cpt_delete\', 10, 3);