Skip to content

Instantly share code, notes, and snippets.

@dlxsnippets
Created February 12, 2023 22:27
Show Gist options
  • Save dlxsnippets/85ab21418c7a9f0fd376e2824995feda to your computer and use it in GitHub Desktop.
Save dlxsnippets/85ab21418c7a9f0fd376e2824995feda to your computer and use it in GitHub Desktop.
How to Redirect After Plugin Activation
<?php
/**
* Plugin Name: Memberships Plus
* Plugin URI: https://dlxplugins.com/plugins/
* Description: A Pro membership plugin.
* Version: 1.0.0
* Requires at least: 5.8
* Requires PHP: 7.2
* Author: DLX Plugins
* Author URI: https://dlxplugins.com
* License: GPL v2 or later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
*
* @package MembershipsPlus
*/
/**
* Callback for adding an admin menu.
*/
function memberships_plus_add_admin_menu() {
add_options_page(
'Memberships Plus',
'Memberships Plus',
'manage_options',
'memberships-plus',
'memberships_plus_options_page'
);
}
add_action( 'admin_menu', 'memberships_plus_add_admin_menu' );
/**
* Callback for the admin panel options.
*/
function memberships_plus_options_page() {
?>
<div class="wrap">
<h1>Memberships Plus</h1>
<p>Welcome to Memberships Plus.</p>
</div>
<?php
}
register_activation_hook( __FILE__, 'memberships_plus_plugin_activate' );
/**
* Add an option upon activation to read in later when redirecting.
*/
function memberships_plus_plugin_activate() {
if ( memberships_plus_can_redirect_on_activation() ) {
add_option( 'memberships_plus_plugin_do_activation_redirect', sanitize_text_field( __FILE__ ) );
}
}
/**
* Determine if a user can be redirected or not.
*
* @return true if the user can be redirected. false if not.
*/
function memberships_plus_can_redirect_on_activation() {
// If plugin is activated in network admin options, skip redirect.
if ( is_network_admin() ) {
return false;
}
// Skip redirect if WP_DEBUG is enabled.
if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
return false;
}
// Determine if multi-activation is enabled.
$maybe_multi = filter_input( INPUT_GET, 'activate-multi', FILTER_VALIDATE_BOOLEAN );
if ( $maybe_multi ) {
return false;
}
// All is well. Can redirect.
return true;
}
add_action( 'admin_init', 'memberships_plus_plugin_activate_redirect' );
/**
* Redirect a user to the admin panel after activation.
*/
function memberships_plus_plugin_activate_redirect() {
if ( memberships_plus_can_redirect_on_activation() && is_admin() ) {
// Read in option value.
if ( __FILE__ === get_option( 'memberships_plus_plugin_do_activation_redirect' ) ) {
// Delete option value so no more redirects.
delete_option( 'memberships_plus_plugin_do_activation_redirect' );
// Get redirect URL.
$redirect_url = admin_url( 'options-general.php?page=memberships-plus' );
wp_safe_redirect(
esc_url( $redirect_url )
);
exit;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment