我正在使用 get_delete_post_link 从前端删除自定义帖子,但删除后我得到 404 页面。自定义帖子删除后如何重定向到首页?
我在functions.php中插入了这段代码:
function wp_delete_post_link($link = 'Delete Post', $before = '', $after = '') {
global $post;
$link = "<a href='" . wp_nonce_url( get_bloginfo('url') . "/wp-admin/post.php?action=delete&post=" .
$post->ID, 'delete-post_' . $post->ID) . "'>".$link."</a>";
echo $before . $link . $after;
}
之后我创建了短代码来生成删除按钮:
function wpc_elementor_shortcode( $atts ) {
wp_delete_post_link();
}
add_shortcode( 'my_shortcode', 'wpc_elementor_shortcode');
有没有办法改进这段代码,实现删除后重定向?
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
试试这个:
/** * template_redirect Action Hook. * Redirect users to home page * after deleting a custom post type post. */ function redirect_on_delete() { // Custom post type plural name or rewrite slug name. $custom_post_type = 'CUSTOM_POST_TYPE'; $regex = "/" . $custom_post_type . ".*" . preg_quote( "/?deleted=", "/" ) . "\d+" . "/i"; if ( preg_match( $regex, $_SERVER["REQUEST_URI"] ) ) { \nocache_headers(); if ( \wp_safe_redirect( esc_url( get_home_url() ) ) ) { exit; }; } } add_action( 'template_redirect', 'redirect_on_delete', 10, 1 );我尝试了许多代码片段来在删除自定义帖子后进行重定向,但没有一个起作用。所以我尝试了另一种方法:将 404 页面重定向到我为编辑器角色用户构建的自定义前端编辑器仪表板。代码如下:
function editor_redirect_404() { global $wp_query; if ( $wp_query->is_404 ) { wp_redirect( home_url( '/dashboard/' ) ); exit; } } add_action('template_redirect', 'editor_redirect_404', 1);我不希望网站的访问者遇到这种情况(他们有常规的 404 页面),因此仅当用户登录并具有编辑者角色时才会应用此重定向。这是通过使用 WPCodeBox 插件中的条件生成器来实现的。