wp_trash_post()WP 2.9.0

Move a post or page to the Trash

If Trash is disabled, the post or page is permanently deleted.

Hooks from the function

Return

WP_Post|false|null. Post data on success, false or null on failure.

Usage

wp_trash_post( $post_id );
$post_id(int)
Post ID.
Default: ID of the global $post if EMPTY_TRASH_DAYS equals true

Examples

0

#1 Move the post to the trash

If the trash is enabled, we will move the post with ID=15 to the trash. The post will remain in the trash for 30 days, during this time we can restore it. After 30 days, the post will be deleted completely by WordPress.

$post_id = 15;
wp_trash_post( $post_id );

If trash feature is not enabled, then wp_delete_post() function will be called.

Notes

Changelog

Since 2.9.0 Introduced.

wp_trash_post() code WP 6.5.2

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;
}