我创建了一个新的自定义帖子类型,用户可以从前端添加新帖子,它可以根据需要工作。现在,我正在尝试添加一个要删除的按钮。这是按钮触发的代码:
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 );
一切似乎都如我所愿(帖子拇指被删除,第二幅图像被删除,帖子被删除,用户被重定向),但调试时出现了一个错误。日志上写着:
[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
如何删除自定义帖子类型的帖子而不出现该错误?我错过了什么?
SO网友:Rafa Carvalhido
我相信我找到了问题所在。由于wp\\u delete\\u post在重定向之前,WordPress尝试重新加载不存在的页面(和注释,因为它们是通过命令自动删除的),这导致了错误。
新代码就是这样,它不会产生错误:
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;
此外,您可能会注意到我添加了
exit
到代码。这就是遵循指导原则
in here.