Here’s the situation: a client of mine wanted to be redirected to All Posts page (/wp-admin/edit.php?post_type=) when a post is updated or published. There are many solutions over the internet, Stackoverflow etc. Most of them are dated and not working since WordPress and Gutenberg updated their cores in 2020.

Auto redirect to wp-admin/edit.php when update or publish post

First you need a PHP to add the jQuery in the footer. Code goes in functions.php.

Next is the actual redirecting part. The class .editor-post-publish-button__button is the class of the Update/Publish button in WordPress.

We use setTimeout twice because of timing issue. The first setTimeout is used to load the code after everything is loaded on the page.

The second setTimeout is needed to delay page rediretion, so Ajax can actually update/publish the post and for better user experience. So here’s the script for redirecting to App posts after post is published or updated. By the way the code works for posts, pages, custom post types etc.

Redirect to dashboard after post publish/update – PHP, jQuery script

// Redirect to All posts dashboard after post update/publish
function webroomtech_redirect_to_post_list() {
?>
<script>
// On "publish / update / submit changes" button click, redirect to cpt listing
jQuery(document).ready(function($) {

    // Getting the post type to work for post, pages, custom post types etc.
    let postType = document.querySelector('form.metabox-base-form input#post_type').value;

    var url = '/wp-admin/edit.php?post_type=' + postType;

    setTimeout(function() {
        $('.editor-post-publish-button__button').on('click', function() {
            setTimeout(function() {
                $.ajax({
                    success: function() {
                        window.location.href = url;
                    }
                });
            }, 2000);

        });
    }, 5000);
  
});
</script>
<?php
}
add_action( 'admin_print_footer_scripts', 'webroomtech_redirect_to_post_list' );

Recent Articles




Related Articles

If you enjoyed reading this, then please explore our other articles below: