0

I'm trying to create a short code to delete post that user publish from the front end of my site.

I've tried the short-code below but I keep getting the error "The link you followed has expired." Kindly see image screenshot below.

  //Shortcode to delete post
    function delete_my_posts() {
        ob_start();

            $url = get_bloginfo('url');
     if (current_user_can('edit_post', $post->ID)){
       echo '<a class="delete-post" rel=”nofollow” href="';
       echo wp_nonce_url("$url/wp-admin/post.php?action=trash&post=$id", 'delete-post_' . $post->ID);
       echo '">Delete post</a>';
     }

       return ob_get_clean();    
    }
    add_shortcode( 'delete_me', 'delete_my_posts' );

Screenshot: https://imgur.com/a/PMB1uU4

Can someone kindly advise on this error?

Thanks

0

Following is the reformatted version of your code. get_delete_post_link() is used for fetching delete post URL so that we dont have to worry about nonce stuff. global $post is kept to avoid PHP notice which is currently there in your code. Please check it.

function wpso_delete_my_posts() {
    global $post;
    ob_start();
    if ( current_user_can('delete_posts', $post->ID ) ) {
        echo '<a class="delete-post" rel="nofollow" href="' . esc_url( get_delete_post_link( $post->ID ) ) . '">Delete Post</a>';
    }
    return ob_get_clean();
}
add_shortcode( 'delete_me', 'wpso_delete_my_posts' );
  • Great! It works fine. How would I go about adding a redirect after the post is deleted? I tried using the wp_redirect function to redirect to another page after deletion, but instead, when I click the delete post link it redirects before deleting. I placed the wp_redirect function both at the bottom and at the top of the return statement for the shortcode but it didn't work. Any ideas as to where I can place the function? – Kendell Daniel May 16 at 22:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.