函数文档

get_delete_post_link()

💡 云策文档标注

概述

get_delete_post_link() 函数用于生成删除文章的链接,适用于 WordPress 循环内外和所有文章类型。它基于用户权限和文章状态(如是否强制删除)返回安全的 URL。

关键要点

  • 函数返回删除文章的链接 URL,参数包括文章 ID 或对象、废弃参数(已弃用)和是否强制删除标志。
  • 使用前需检查用户权限(current_user_can('delete_post'))和文章类型对象是否存在。
  • 链接生成涉及 add_query_arg()、admin_url() 和 wp_nonce_url() 以确保安全性。
  • 可通过 apply_filters('get_delete_post_link') 钩子自定义链接。

注意事项

对于自定义文章类型,必须将 register_post_type() 的 "show_ui" 参数设置为 true,否则链接可能无法正常工作。


📄 原文内容

Retrieves the delete posts link for post.

Description

Can be used within the WordPress loop or outside of it, with any post type.

Parameters

$postint|WP_Postoptional
Post ID or post object. Default is the global $post.
$deprecatedstringoptional
Not used.
$force_deletebooloptional
Whether to bypass Trash and force deletion.

Default:false

Return

string|void The delete post link URL for the given post.

Source

function get_delete_post_link( $post = 0, $deprecated = '', $force_delete = false ) {
	if ( ! empty( $deprecated ) ) {
		_deprecated_argument( __FUNCTION__, '3.0.0' );
	}

	$post = get_post( $post );

	if ( ! $post ) {
		return;
	}

	$post_type_object = get_post_type_object( $post->post_type );

	if ( ! $post_type_object ) {
		return;
	}

	if ( ! current_user_can( 'delete_post', $post->ID ) ) {
		return;
	}

	$action = ( $force_delete || ! EMPTY_TRASH_DAYS ) ? 'delete' : 'trash';

	$delete_link = add_query_arg( 'action', $action, admin_url( sprintf( $post_type_object->_edit_link, $post->ID ) ) );

	/**
	 * Filters the post delete link.
	 *
	 * @since 2.9.0
	 *
	 * @param string $link         The delete link.
	 * @param int    $post_id      Post ID.
	 * @param bool   $force_delete Whether to bypass the Trash and force deletion. Default false.
	 */
	return apply_filters( 'get_delete_post_link', wp_nonce_url( $delete_link, "$action-post_{$post->ID}" ), $post->ID, $force_delete );
}

Hooks

apply_filters( ‘get_delete_post_link’, string $link, int $post_id, bool $force_delete )

Filters the post delete link.

Changelog

Version Description
2.9.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Be careful, if you use this function with a custom post type, you must define the “show_ui” parameter of the register_post_type() function to true.

    With “show_ui” parameter to false, link doesn’t work
    https://example.com/wp-admin/?action=delete&_wpnonce=bb70aa97e2

    With “show_ui” parameter to true, link works
    https://example.com/wp-admin/post.php?post=1234&action;=delete&_wpnonce=87d5108013