wp_trash_post()
云策文档标注
概述
wp_trash_post() 函数用于将文章或页面移至回收站,若回收站功能被禁用则永久删除。该函数处理文章状态变更、元数据更新和相关钩子触发。
关键要点
- 参数 $post_id 可选,默认为全局 $post 的 ID,前提是 EMPTY_TRASH_DAYS 为真
- 返回值:成功时返回 WP_Post 对象,失败时返回 false 或 null
- 内部逻辑:检查 EMPTY_TRASH_DAYS 常量,若为假则调用 wp_delete_post() 永久删除
- 钩子:包括 pre_trash_post 过滤器、wp_trash_post 和 trashed_post 动作钩子
- 相关函数:涉及 wp_update_post()、wp_trash_post_comments() 等
代码示例
// 将 ID 为 1 的文章移至回收站
wp_trash_post( 1 );注意事项
- 使用前需确保文章存在且状态非 'trash',否则可能返回 false
- 回收站功能依赖于 EMPTY_TRASH_DAYS 常量设置,开发者应检查环境配置
原文内容
Moves a post or page to the Trash
Description
If Trash is disabled, the post or page is permanently deleted.
See also
Parameters
$post_idintoptional-
Post ID. Default is the ID of the global
$postifEMPTY_TRASH_DAYSequals true.
Source
function wp_trash_post( $post_id = 0 ) {
if ( ! EMPTY_TRASH_DAYS ) {
return wp_delete_post( $post_id, true );
}
$post = get_post( $post_id );
if ( ! $post ) {
return $post;
}
if ( 'trash' === $post->post_status ) {
return false;
}
$previous_status = $post->post_status;
/**
* Filters whether a post trashing should take place.
*
* @since 4.9.0
* @since 6.3.0 Added the `$previous_status` parameter.
*
* @param bool|null $trash Whether to go forward with trashing.
* @param WP_Post $post Post object.
* @param string $previous_status The status of the post about to be trashed.
*/
$check = apply_filters( 'pre_trash_post', null, $post, $previous_status );
if ( null !== $check ) {
return $check;
}
/**
* Fires before a post is sent to the Trash.
*
* @since 3.3.0
* @since 6.3.0 Added the `$previous_status` parameter.
*
* @param int $post_id Post ID.
* @param string $previous_status The status of the post about to be trashed.
*/
do_action( 'wp_trash_post', $post_id, $previous_status );
add_post_meta( $post_id, '_wp_trash_meta_status', $previous_status );
add_post_meta( $post_id, '_wp_trash_meta_time', time() );
$post_updated = wp_update_post(
array(
'ID' => $post_id,
'post_status' => 'trash',
)
);
if ( ! $post_updated ) {
return false;
}
wp_trash_post_comments( $post_id );
/**
* Fires after a post is sent to the Trash.
*
* @since 2.9.0
* @since 6.3.0 Added the `$previous_status` parameter.
*
* @param int $post_id Post ID.
* @param string $previous_status The status of the post at the point where it was trashed.
*/
do_action( 'trashed_post', $post_id, $previous_status );
return $post;
}
Hooks
- apply_filters( ‘pre_trash_post’, bool|null $trash, WP_Post $post, string $previous_status )
-
Filters whether a post trashing should take place.
- do_action( ‘trashed_post’, int $post_id, string $previous_status )
-
Fires after a post is sent to the Trash.
- do_action( ‘wp_trash_post’, int $post_id, string $previous_status )
-
Fires before a post is sent to the Trash.
Changelog
| Version | Description |
|---|---|
| 2.9.0 | Introduced. |
Skip to note 2 content
Codex
Basic Example
Trash the default WordPress Post, “Hello World,” which has an ID of ‘1’.