Created
September 24, 2021 17:20
-
-
Save donmhico/fbbbfafb923e62765107c3c94aa45d80 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
add_action( 'edit_form_top', 'add_parameters_to_preserve_in_post_form' ); | |
/** | |
* Add a new input in Post form. | |
* | |
* @see https://developer.wordpress.org/reference/hooks/edit_form_top/ | |
* | |
* @return void | |
*/ | |
function add_parameters_to_preserve_in_post_form() : void { | |
$back_to_plugin = filter_input( INPUT_GET, 'go-back-to-plugin', FILTER_SANITIZE_STRING ); | |
if ( empty( $back_to_plugin ) || '1' !== $back_to_plugin ) { | |
return; | |
} | |
?> | |
<input | |
type="hidden" | |
id="go-back-to-plugin" | |
name="go-back-to-plugin" | |
value="1" | |
/> | |
<?php | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment