This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.
init action
The ‘init’ action hook is your go-to when WordPress is gearing up and loading all the necessary PHP files, plugins, and themes in the background. It’s a fantastic hook to register your plugin, widgets, or assets in functions.php.
To get started with the init action, you need to register it using add_action
. You can place this code in the functions.php of your active theme or within a custom WordPress Plugin. At WePlugins, we always recommend creating a custom WordPress Plugin when using hooks to avoid any issues during theme updates.
Example 1: Basic Hook Usage
In this live example, we’ve defined a function weplugins_execute_on_init_event
and registered it using add_action
. The first parameter init is the name of the hook. The second parameter weplugins_execute_on_init_event is the function that needs to be called.
function weplugins_execute_on_init_event(){ // Code you want to execute during the init event } // add the action add_action("init", "weplugins_execute_on_init_event");
Example 2: Registering a Custom Post Type
Here’s how you can register a custom post type using the init hook.
function weplugins_custom_post_type_registration() { $args = array( 'public' => true, 'label' => 'Custom Post Type' // Add more arguments as needed ); register_post_type('custom_post', $args); } add_action('init', 'weplugins_custom_post_type_registration');
Example 3: Enqueuing a Custom Stylesheet
This example demonstrates how to enqueue a custom stylesheet using the init hook.
function weplugins_enqueue_custom_stylesheet() { wp_enqueue_style('custom-style', get_template_directory_uri() . '/css/custom-style.css', array(), '1.0', 'all'); } add_action('init', 'weplugins_enqueue_custom_stylesheet');
If you ever need to remove a registered hook, you can use remove_action like this:
remove_action("init", "weplugins_execute_on_init_event");
Ensure you provide the same callback function name, priority, and number of arguments when removing the hook callback.
If you need any customization or help with using this hook, feel free to Contact Us.
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.