我正在使用
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');
有没有办法改进这段代码,实现删除后的重定向?
试试这个:
/**
* 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 );