本文详解如何在wordpress前端删除文章后,通过wp_redirect()正确跳转至对应作者的归档页面(如/author/username/),解决因url拼接缺失路径导致重定向失效的问题。
本文详解如何在wordpress前端删除文章后,通过wp_redirect()正确跳转至对应作者的归档页面(如/author/username/),解决因url拼接缺失路径导致重定向失效的问题。
在WordPress开发中,使用wp_redirect()进行页面跳转是常见需求,但其生效有严格前提:必须在任何输出(包括HTML、空白符、PHP警告)发送到浏览器之前执行。你提供的代码中存在两个关键问题,直接导致重定向失败:
✅ 正确做法如下:
add_action( 'trashed_post', 'dex_redirect_after_trashing', 10, 1 );function dex_redirect_after_trashing( $post_id ) { // 确保$post_id有效且为整数 if ( ! $post_id || ! is_numeric( $post_id ) ) { return; } $post = get_post( $post_id ); if ( ! $post || $post->post_author <= 0 ) { return; } $author_nicename = get_user_by( 'id', $post->post_author )->user_nicename; $target_url = home_url( '/author/' . urlencode( $author_nicename ) ); wp_safe_redirect( $target_url ); exit;}
⚠️ 注意事项:
通过以上修正,即可稳定实现“用户删除自己文章后,自动跳转至其个人作者归档页”的功能,兼顾兼容性与安全性。
立即学习“前端免费学习笔记(深入)”;