How to automatically redirect to custom admin menu after plugin activation?

I need a function to redirect user to the plugin settings page, right after plugin activation.

I use this function to create a custom menu settings page:

// add option page menu link
function axl_ads_add_admin_menu() { 
    $icon = 'dashicons-align-left"';
      add_menu_page( 'AXL Ads', 'AXL Ads', 'manage_options', 'axl_ads',  array($this, 'axl_ads_options_page'), $icon, '3' );
  }

And my settings page url is: wp-admin/admin.php?page=axl_ads

Any help with this, please?

Topic plugin-options plugins Wordpress

Category Web


You can use register_activation_hook(). Add this to your plugin, tested and works.

register_activation_hook(__FILE__, 'redirect_after_activation');

function redirect_after_activation() {
    add_option('redirect_after_activation_option', true);
}

add_action('admin_init', 'activation_redirect');

function activation_redirect() {
    if (get_option('redirect_after_activation_option', false)) {
        delete_option('redirect_after_activation_option');
        exit(wp_redirect(admin_url( 'wp-admin/admin.php?page=axl_ads' )));
    }
}

There is a hook named register_activation_hook that usually works at the time of the plugin activation. This function should be called within the plugins_loaded hook. So,

Firstly, call the activation hook -

function fn_name(){
register_activation_hook(__FILE__,'activation_fn');
}
add_action('plugins_loaded','fn_name');

Now, you need to call the function -

function activation_fn(){
 wp_redirect($target_url);
}

here, wp_redirect($url) is used that redirect you to a specific location. So, simply add your target URL inside the wp_redirect() function.

As a result, when your plugin will be activated, it will automatically redirect to you to the specific location.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.