使用权限检查、数据验证、安全输入、安全输出和非ces的完整示例:
/**
* 根据主页url生成删除链接。
*
* @param string $content 现有内容。
*
* @return string|null
*/
function wporg_generate_delete_link( $content ) {
// 仅针对单篇文章页面运行。
if ( is_single() && in_the_loop() && is_main_query() ) {
// 添加查询参数:action, post, nonce
$url = add_query_arg(
[
'action' => 'wporg_frontend_delete',
'post' => get_the_ID(),
'nonce' => wp_create_nonce( 'wporg_frontend_delete' ),
], home_url()
);
return $content . ' <a href="' . esc_url( $url ) . '">' . esc_html__( 'Delete Post', 'wporg' ) . '</a>';
}
return null;
}
/**
* 请求处理器
*/
function wporg_delete_post() {
if ( isset( $_GET['action'] )
&& isset( $_GET['nonce'] )
&& 'wporg_frontend_delete' === $_GET['action']
&& wp_verify_nonce( $_GET['nonce'], 'wporg_frontend_delete' ) ) {
// 验证我们是否有文章id。
$post_id = ( isset( $_GET['post'] ) ) ? ( $_GET['post'] ) : ( null );
// 验证是否存在具有该编号的文章。
$post = get_post( (int) $post_id );
if ( empty( $post ) ) {
return;
}
// 删除文章。
wp_trash_post( $post_id );
// 重定向到管理页面。
$redirect = admin_url( 'edit.php' );
wp_safe_redirect( $redirect );
// 完成。
die;
}
}
/**
* 添加删除文章能力
*/
add_action('plugins_loaded', 'wporg_add_delete_post_ability');
function wporg_add_delete_post_ability() {
if ( current_user_can( 'edit_others_posts' ) ) {
/**
* 在文章内容的末尾添加删除链接。
*/
add_filter( 'the_content', 'wporg_generate_delete_link' );
/**
* 使用 init hook 注册我们的请求处理器。
*/
add_action( 'init', 'wporg_delete_post' );
}
}