search

Home  >  Q&A  >  body text

Remove custom post type and redirect to home page

<p>I'm using <code>get_delete_post_link</code> to delete a custom post from the frontend, but after deleting I'm getting a 404 page. How to redirect to the homepage after deleting a custom post? </p> <p>I inserted this code in functions.php: </p> <pre class="brush:php;toolbar:false;">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; }</pre> <p>Then I created a shortcode to generate the delete button: </p> <pre class="brush:php;toolbar:false;">function wpc_elementor_shortcode( $atts ) { wp_delete_post_link(); } add_shortcode( 'my_shortcode', 'wpc_elementor_shortcode');</pre> <p>Is there any way to improve this code to redirect after deletion? </p>
P粉590428357P粉590428357453 days ago510

reply all(2)I'll reply

  • P粉020556231

    P粉0205562312023-09-05 00:57:37

    Try this:

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

    reply
    0
  • P粉609866533

    P粉6098665332023-09-05 00:40:08

    I tried many code snippets to redirect after deleting the custom post but none of them worked. So I tried another approach: redirecting the 404 page to a custom front-end editor dashboard I built for editor role users. code show as below:

    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 visitors to the site to encounter this (they have regular 404 pages), so this redirect will only be applied if the user is logged in and has the editor role. This is achieved by using conditional generators from the WPCodeBox plugin.

    reply
    0
  • Cancelreply