Search code examples
phpwordpresscustom-post-type

Delete custom post type and redirect to homepage


I'm using get_delete_post_link to delete custom post from the front-end, but after deletion I get 404 page. How can I redirect to homepage after custom post is deleted?

I inserted in functions.php this code:

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&amp;post=" . 
    $post->ID, 'delete-post_' . $post->ID) . "'>".$link."</a>";
    echo $before . $link . $after;
}

And after that I created shortcode to generate delete button:

function wpc_elementor_shortcode( $atts ) {
    wp_delete_post_link();
}
add_shortcode( 'my_shortcode', 'wpc_elementor_shortcode');

Is there a way to improve this code to achieve redirection after deletion?


Solution

  • I tried many code snippets for redirecting after deletion a custom post, but none of them worked. So I tried another approach: to redirect 404 page to custom frontend editor dashboard which I built for the Editor role user. Here's the code:

    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);
    

    I don't want the visitors of the site to experience this (they have regular 404 page), so this redirection is applied only if user is logged in and have the Editor role. This is achieved by using condition builder in WPCodeBox plugin.