Exciting News! Flipper Code is now WePlugins! Same commitment to excellence, brand new identity.

How to use admin_init filter in WordPress

Sandeep Kumar Mishra
Sandeep Kumar Mishra
June 7, 2023
5 minutes read

 

admin_init filter

Note, this does not just run on user-facing admin screens. It runs on admin-ajax.php and admin-post.php as well.

To use admin_init filter, first you have to register it using add_filter. You can write this code into functions.php of your activated theme or in a custom WordPress Plugin.

We always prefer to create a custom WordPress Plugin while using hooks so nothing breaks when you update your WordPress Theme in the future.

In the below live example, we have defined a function weplugins_modify_admin_init_defaults and we registered it using add_filter. The first parameter admin_init is the name of the hook, the second parameter weplugins_modify_admin_init_defaults is the name of the function which needs to be called, the third parameter is the priority of calling the hook if the same hook is used multiple times, and the last parameter is the number of arguments (if any) to be passed in the registered function.

Sometimes, you have to remove a registered hook so you can use remove_filter to remove admin_init filter.

Example 1: Restrict Access to Admin Screens

This example shows how to restrict access to the administration screens, allowing only administrators. Non-admin users are shown a message instead, although Ajax requests are still allowed for all users.

    function weplugins_restrict_admin() {
        // Implementation code here
    }
    add_filter("admin_init", "weplugins_restrict_admin");
    

Example 2: Modify Admin Init Defaults

Below is an example of how you can use this hook to modify admin init defaults.

    function weplugins_modify_admin_init_defaults() {
        $viewport_meta = ''; // Update the $viewport_meta variable according to your website requirements
        return $viewport_meta; 
    }
    // add the filter
    add_filter("admin_init", "weplugins_modify_admin_init_defaults");
    

Example 3: Remove a Hook Callback

To remove a hook callback, use the example below. Make sure to provide the same callback function name, priority, and number of arguments while removing the hook callback.

    remove_filter("admin_init", "weplugins_modify_admin_init_defaults");
    

Access Premium WordPress Plugins

Contact Us

If you’re having any trouble using this hook or need customization, please Contact Us and we’d be happy to assist you.

Sandeep Kumar Mishra

Sandeep Kumar Mishra

Sandeep Kumar Mishra writes about WordPress and Artificial Intelligence, offering tips and guides to help you master your website and stay updated with the latest tech trends.

Explore the latest in WordPress

Trying to stay on top of it all? Get the best tools, resources and inspiration sent to your inbox every Wednesday.