0

I created a new custom post type that users can add new post from frontend and it works as desired. Now, I´m trying to add a button to delete. This is the code triggered by the button:

    if( has_post_thumbnail( $post_id ) ) {
        $main_image_id = get_post_thumbnail_id( $post_id );
        wp_delete_attachment( $main_image_id , true );
    }
    if( get_post_meta( $post_id , 'token_personagem' , true ) ) {
        $token_id = get_post_meta( $post_id , 'token_personagem' , true );
        wp_delete_attachment( $token_id , true );
    }
    wp_delete_post( $post_id );
    wp_redirect( $url );

Everything seems to work as I wanted (post thumb is deleted, second image is deleted, post is deleted and user is redirected), but an error comes up on debug.log which says:

[16-May-2021 23:13:34 UTC] PHP Stack trace:
[16-May-2021 23:13:34 UTC] PHP   1. {main}() Z:\WP-DesktopServer\forjadosmestres.dev.cc\index.php:0
[16-May-2021 23:13:34 UTC] PHP   2. require() Z:\WP-DesktopServer\forjadosmestres.dev.cc\index.php:17
[16-May-2021 23:13:34 UTC] PHP   3. require_once() Z:\WP-DesktopServer\forjadosmestres.dev.cc\wp-blog-header.php:19
[16-May-2021 23:13:34 UTC] PHP   4. include() Z:\WP-DesktopServer\forjadosmestres.dev.cc\wp-includes\template-loader.php:106
[16-May-2021 23:13:34 UTC] PHP   5. comments_template() Z:\WP-DesktopServer\forjadosmestres.dev.cc\wp-content\themes\square-child\single-personagem.php:28
[16-May-2021 23:13:34 UTC] PHP   6. require() Z:\WP-DesktopServer\forjadosmestres.dev.cc\wp-includes\comment-template.php:1556
[16-May-2021 23:13:34 UTC] PHP   7. comment_form() Z:\WP-DesktopServer\forjadosmestres.dev.cc\wp-content\themes\square\comments.php:78
[16-May-2021 23:13:34 UTC] PHP   8. comments_open() Z:\WP-DesktopServer\forjadosmestres.dev.cc\wp-includes\comment-template.php:2327

How can I delete custom post type posts without that error? What am I missing?

1

I believe I found the problem. Since the wp_delete_post was before the redirect, WordPress tried to reload an inexistent page (and comments, since they are deleted automaticaly with the command) and that generated the error.

The new code is as such and it's not generating errors:

        if( has_post_thumbnail( $post_id ) ) {
            $imagem_principal_id = get_post_thumbnail_id( $post_id );
            wp_delete_attachment( $imagem_principal_id , true );
        }
        if( get_post_meta( $post_id , 'token_personagem' , true ) ) {
            $token_id = get_post_meta( $post_id , 'token_personagem' , true );
            wp_delete_attachment( $token_id , true );
        }
        wp_redirect( $url );
        wp_delete_post( $post_id );
        exit;

Also, you may notice I added exit to the code. That is to follow guidelines in here.

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.