機能チェック、データ検証、安全な入力、安全な出力、ノンスを使用した完全な例:

    1. /**
    2. * Generate a Delete link based on the homepage url.
    3. *
    4. * @param string $content Existing content.
    5. *
    6. * @return string|null
    7. */
    8. function wporg_generate_delete_link( $content ) {
    9. // Run only for single post page.
    10. if ( is_single() && in_the_loop() && is_main_query() ) {
    11. // Add query arguments: action, post, nonce
    12. $url = add_query_arg(
    13. [
    14. 'action' => 'wporg_frontend_delete',
    15. 'post' => get_the_ID(),
    16. 'nonce' => wp_create_nonce( 'wporg_frontend_delete' ),
    17. ], home_url()
    18. );
    19. return $content . ' <a href="' . esc_url( $url ) . '">' . esc_html__( 'Delete Post', 'wporg' ) . '</a>';
    20. }
    21. return null;
    22. }
    23. /**
    24. * Request handler
    25. */
    26. function wporg_delete_post() {
    27. if ( isset( $_GET['action'] )
    28. && isset( $_GET['nonce'] )
    29. && 'wporg_frontend_delete' === $_GET['action']
    30. && wp_verify_nonce( $_GET['nonce'], 'wporg_frontend_delete' ) ) {
    31. // Verify we have a post id.
    32. $post_id = ( isset( $_GET['post'] ) ) ? ( $_GET['post'] ) : ( null );
    33. // Verify there is a post with such a number.
    34. $post = get_post( (int) $post_id );
    35. if ( empty( $post ) ) {
    36. return;
    37. }
    38. // Delete the post.
    39. wp_trash_post( $post_id );
    40. // Redirect to admin page.
    41. $redirect = admin_url( 'edit.php' );
    42. wp_safe_redirect( $redirect );
    43. // We are done.
    44. die;
    45. }
    46. }
    47. /**
    48. * Add delete post ability
    49. */
    50. add_action('plugins_loaded', 'wporg_add_delete_post_ability');
    51. function wporg_add_delete_post_ability() {
    52. if ( current_user_can( 'edit_others_posts' ) ) {
    53. /**
    54. * Add the delete link to the end of the post content.
    55. */
    56. add_filter( 'the_content', 'wporg_generate_delete_link' );
    57. /**
    58. * Register our request handler with the init hook.
    59. */
    60. add_action( 'init', 'wporg_delete_post' );
    61. }
    62. }