Hi @scooterlord,
Thanks for following up. Probably your best bet is to use an Ajax callback to call wp_trash_post(), which would trash the post and then after 30 days it was just get deleted. The link generated by get_delete_post_link() has some internal handling to decide whether to trash or delete a post and I think your safest best is just to stick with trashing them.
In practice, the way that might look would be something like the following (untested):
In your template:
<?php if ( current_user_can( 'delete_post', $post->ID ) ) : ?>
<button id="my-delete-post-button" data-post_id="<?php echo esc_attr( $post->ID ); ?>" data-nonce="<?php echo esc_attr( wp_create_nonce( 'my-delete-post-nonce' ) ); ?>">Delete</button>
<?php endif; ?>
And then in your theme’s functions.php file, you’d first inject some JavaScript to handle the Ajax (again, untested):
<?php
/**
* Injects jQuery to handle for the Ajaxified post delete button.
*/
function my_post_delete_button_script() {
if ( ! is_singular( 'post' ) ) {
return;
}
?>
( function( $ ) {
$( '#my-delete-post-button' ).on( 'click', function( event ) {
event.preventDefault();
$.ajax( {
type: 'POST',
url: ajaxurl,
data: {
action: 'my_delete_post_action',
post_id: $( this ).data( 'post_id' ),
nonce: $( this ).data( 'nonce' )
},
dataType: "json",
success: function( response ) {
if ( response.success && 'undefined' !== response.success.data.redirect ) {
// Redirect the user.
window.location.replace( response.success.data.redirect );
} else {
console.log( response );
}
}
} ).fail( function( response ) {
if ( window.console && window.console.log ) {
console.log( response );
}
} );
} );
} )( jQuery );
<?php
}
add_action( 'wp_head', 'my_post_delete_button_script' );
?>
And then your Ajax callback:
<?php
/**
* My post delete button Ajax handler.
*/
function my_delete_post_action() {
if ( ! isset( $_REQUEST['nonce'] )
|| ( isset( $_REQUEST['nonce'] ) && false === wp_verify_nonce( $_REQUEST['nonce'], 'my-delete-post-nonce' ) )
) {
wp_send_json_error( new \WP_Error( 'invalid_request', 'You do not have permission to perform this action.' ) );
}
$post_id = empty( $_REQUEST['post_id'] ) ? 0 : intval( $_REQUEST['post_id'] );
if ( 0 === $post_id ) {
wp_send_json_error( new \WP_Error( 'missing_post_id', 'A post ID is required to proceed.' ) );
}
if ( current_user_can( 'delete_post', $post_id ) ) {
$trashed = wp_trash_post( $post_id );
if ( $trashed ) {
wp_send_json_success( array( 'redirect' => home_url() ));
}
}
wp_send_json_error( array( 'redirect' => '' ) );
}
add_action( 'wp_ajax_my_delete_post_action', 'my_delete_post_action' );
?>
Hope that helps point you in the right direction.
-
This reply was modified 4 years, 7 months ago by
Drew Jaynes.
-
This reply was modified 4 years, 7 months ago by
Drew Jaynes.