钩子文档

wp_trash_post

💡 云策文档标注

概述

wp_trash_post 是一个 WordPress 动作钩子,在文章被移至回收站之前触发。它允许开发者在文章被删除前执行自定义代码,例如处理多篇文章的批量操作。

关键要点

  • 这是一个动作钩子,用于在文章被移至回收站前执行操作。
  • 参数包括 $post_id(文章 ID)和 $previous_status(文章之前的状态)。
  • 从 WordPress 6.3.0 版本开始,新增了 $previous_status 参数。
  • 可用于处理批量删除文章的场景,例如通过 $_GET['post'] 获取多篇文章 ID。

代码示例

function wpdocs_trash_multiple_posts( $post_id = '' ) {
    // 检查是否为批量删除多篇文章
    if ( isset( $_GET['post'] ) && is_array( $_GET['post'] ) ) {
        foreach ( $_GET['post'] as $post_id ) {
            wpdocs_your_function( $post_id );
        }
    } else {
        wpdocs_your_function( $post_id );
    }
}
add_action( 'wp_trash_post', 'wpdocs_trash_multiple_posts' );

注意事项

  • 使用此钩子时,需注意安全性和权限验证,避免未授权操作。
  • 在批量处理时,$_GET['post'] 可能包含多个文章 ID,应循环处理。

📄 原文内容

Fires before a post is sent to the Trash.

Parameters

$post_idint
Post ID.
$previous_statusstring
The status of the post about to be trashed.

Source

do_action( 'wp_trash_post', $post_id, $previous_status );

Changelog

Version Description
6.3.0 Added the $previous_status parameter.
3.3.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    To get the id of all posts that have been trashed when selecting multiples, you must use the

    $_GET['post']

    Like that example below:

    function wpdocs_trash_multiple_posts( $post_id = '' ) {
        // Verify if is trashing multiple posts
        if ( isset( $_GET['post'] ) && is_array( $_GET['post'] ) ) {
            foreach ( $_GET['post'] as $post_id ) {
                wpdocs_your_function( $post_id );
            }
        } else {
            wpdocs_your_function( $post_id );
        }
    }
    add_action( 'wp_trash_post', 'wpdocs_trash_multiple_posts' );