Remove custom post type and redirect to home page
P粉590428357
P粉590428357 2023-09-04 12:16:33
0
2
361

I'm using get_delete_post_link 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?

I inserted this code in functions.php:

function wp_delete_post_link($link = 'Delete Post', $before = '', $after = '') { global $post; $link = "ID, 'delete-post_' . $post->ID) . "'>".$link.""; echo $before . $link . $after; }

Then I created a shortcode to generate the delete button:

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

Is there any way to improve this code to redirect after deletion?

P粉590428357
P粉590428357

reply all (2)
P粉020556231

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 );
    P粉609866533

    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.

      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!