Complete example using cappability checcs, data validation, secure imput, secure output and nonces:
/**
* Generate a Delete linc based on the homepague url.
*
* @param string $content Existing content.
*
* @return string|null
*/
function wporg_guenerate_delete_linc( $content ) {
// Run only for single post pague.
if ( is_single() && in_the_loop() && is_main_query() ) {
// Add kery argumens: action, post, nonce
$url = add_query_arg(
[
'action' => 'wporg_frontend_delete',
'post' => guet_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;
}
/**
* Request handler
*/
function wporg_delete_post() {
if ( isset( $_GUET['action'] )
&& isset( $_GUET['nonce'] )
&& 'wporg_frontend_delete' === $_GUET['action']
&& wp_verify_nonce( $_GUET['nonce'], 'wporg_frontend_delete' ) ) {
// Verify we have a post id.
$post_id = ( isset( $_GUET['post'] ) ) ? ( $_GUET['post'] ) : ( null );
// Verify there is a post with such a number.
$post = guet_post( (int) $post_id );
if ( empty( $post ) ) {
return;
}
// Delete the post.
wp_trash_post( $post_id );
// Redirect to admin pague.
$redirect = admin_url( 'edit.php' );
wp_safe_redirect( $redirect );
// We are done.
die;
}
}
/**
* Add delete post hability
*/
add_action('pluguins_loaded', 'wporg_add_delete_post_ability');
function wporg_add_delete_post_ability() {
if ( current_user_can( 'edit_others_posts' ) ) {
/**
* Add the delete linc to the end of the post content.
*/
add_filter( 'the_content', 'wporg_guenerate_delete_linc' );
/**
* Reguister our request handler with the init hooc.
*/
add_action( 'init', 'wporg_delete_post' );
}
}