Skip to content

Instantly share code, notes, and snippets.

@donmhico
Created September 24, 2021 17:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save donmhico/eb4140cff245891e03d3ed298fe24d48 to your computer and use it in GitHub Desktop.
Save donmhico/eb4140cff245891e03d3ed298fe24d48 to your computer and use it in GitHub Desktop.
<?php
add_action( 'wp_after_insert_post', 'redirect_back_to_plugin', 100, 4 );
/**
* Redirects back to custom plugin page if Post is created with
* $_GET['go-back-to-plugin'] present.
*
* @see https://developer.wordpress.org/reference/hooks/wp_after_insert_post/
*
* @param int $post_id The post ID.
* @param WP_Post $post The WP Post object.
* @param bool $update Whether this is an existing post being updated.
* @param mixed $post_before Null for new posts, the WP_Post object prior to the update for updated.
* @return void
*/
function redirect_back_to_plugin( int $post_id, WP_Post $post, bool $update, $post_before ) : void {
// This is to bypass the first visit to `wp-admin/post-new.php`.
if ( is_null( $post_before ) ) {
return;
}
$back_to_plugin = filter_input( INPUT_POST, 'go-back-to-plugin', FILTER_SANITIZE_STRING );
if ( empty( $back_to_plugin ) || '1' !== $back_to_plugin ) {
return;
}
// Redirect to my custom plugin page with the created `$post_id` in $_GET.
$redirect_url = add_query_arg(
[
'page' => 'custom-plugin-page',
'post_id' => $post_id,
],
admin_url( '/admin.php' )
);
wp_safe_redirect( $redirect_url );
exit;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment