Skip to content

Instantly share code, notes, and snippets.

@esedic
Created January 30, 2024 16:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save esedic/90d443f9c30e6c42094a082e86395cec to your computer and use it in GitHub Desktop.
Save esedic/90d443f9c30e6c42094a082e86395cec to your computer and use it in GitHub Desktop.
WordPress hook inside another hook
/*
To use one hook inside another hook in WordPress, you can simply add the second hook as a callback function to the first hook
For example, let's say you want to add a custom function to the init hook, which in turn uses the wp_enqueue_scripts
hook to enqueue some scripts. You can do it like this:
*/
<?php
function my_init_function() {
// do some initialization here
add_action( 'wp_enqueue_scripts', 'my_enqueue_scripts_function' );
}
function my_enqueue_scripts_function() {
// enqueue your scripts here
wp_enqueue_script( 'my-script', 'path/to/my/script.js', array(), '1.0', true );
}
add_action( 'init', 'my_init_function' );
/*
In the above example, my_init_function() is added as a callback function to the init hook.
Inside this function, the add_action() function is used to add my_enqueue_scripts_function() as a callback
to the wp_enqueue_scripts hook. This means that when the init hook is fired, both my_init_function()
and my_enqueue_scripts_function() will be executed.
You can use this same pattern to add any hook inside another hook in WordPress.
Simply define your function, add it as a callback to the first hook, and use add_action() or add_filter()
to add any other hooks that you need inside your function.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment