When anyone presses Publish or Update from the Block Editor in a CPT, I would like them to be redirected to the CPT listing page. (Users are typically editing many of the CPT at once, so this will save them a step – and also prevent them from pressing Update multiple times because they’re not sure whether their edits have been saved.)
I’ve tried two different hooks:
From a 2013 question, redirect_post_location
:
add_filter( 'redirect_post_location', 'wpse_124132_redirect_post_location' );
function wpse_124132_redirect_post_location( $location ) {
if ( isset( $_POST['save'] ) || isset( $_POST['publish'] ) )
return admin_url( 'edit.php?post_type=mycptslug' );
return $location;
}
(I’m wondering if this only affects Core Posts since the hook has "post" in its name? It’s nearly undocumented. Whether it changed since 2013 or just doesn’t work with the new Editor, it didn’t redirect.)
And from my own knowledge of the save_post
hook:
add_action( 'save_post', 'wpse_redirect_to_dashboard', 40, 3 );
function wpse_redirect_to_dashboard( $post_id, $post, $update ) {
global $_POST;
// Since save_post runs 4 times, make sure this is the final run
if( count( $_POST ) > 0 && true === $update && 'mycptslug' === $post->post_type ) {
wp_redirect( admin_url( 'edit.php?post_type=mycptslug' ) ); exit;
}
}
(I have confirmed the if
condition is working as intended – I temporarily logged a success message to a text file, and it was succeeding once each time I pressed Update in the Editor – but it wouldn’t redirect. Also tried redirecting to other URLs in case the admin_url()
part wasn’t working but still no redirect.)
Unfortunately, neither of these work with the Block Editor. The user still stays in the Editor after updating. Is there some other way, such as during CPT registration or some other hook, to successfully send the user on their way after they’ve made edits?
Based on cjbj’s answer, I have this updated code – but it’s still not redirecting. I am not quite sure what loading it late means or how to ensure this fires after the ajax save call. (This works for any post type though):
function wpse_redirect_to_post_list() {
?>
<script>
// Get post type from hidden input
let postType=document.querySelector('form.metabox-base-form input#post_type').value;
// On "publish / update / submit changes" button click, redirect to cpt listing
jQuery( document ).ready( function( $ ) {
var url = '/wp-admin/edit.php?post_type=' + postType;
$( '.editor-post-publish-button__button' ).click( function() {
window.location.href = url;
});
});
</script>
<?php
}
add_action( 'admin_print_footer_scripts', 'wpse_redirect_to_post_list' );