Redirect after deleting post and keep track of pagination

You can use $_SERVER[‘HTTP_REFERER’] to get the URL the user came from.

The following code will find the paged GET variable of the previous URL to determine which page the user was on, then count how many posts are left of that particiular post type (only published) and how many pages are needed to display them all and then take the appropriate redirect action.

function my_deleted_post_handler() 
{
    global $post;

    // URL the user came from
    $referer = $_SERVER['HTTP_REFERER'];

    // the page the user was on
    $page = preg_match('/http:\/\/.*&paged=(\d*)/', $referer, $matches);
    $page_num = $matches[1];

    // how many published posts of $post_type?
    $post_type = $post->post_type; 
    $num_posts = wp_count_posts($post_type)->published;

    // how many pages of 10 items?
    $pages = ceil($num_posts / 10);

    if($pages < $page_num) {
        // the page the user was on doesn't exist anymore
        wp_redirect('http://www.xxxxxx.com/wp-admin/edit.php?post_type=" . $post_type . "&paged=' . $page_num - 1);
    } else {
        // the page still exists
        wp_redirect('http://www.xxxxxx.com/wp-admin/edit.php?post_type=" . $post_type . "&paged=' . $page_num);
    }

    exit();   
}
add_action('deleted_post','my_deleted_post_handler');

Leave a Comment