I am writing a plugin that uses a lot of different action/filter hooks to manipulate different parts of the users.php page (e.g. manage_users_columns, admin_head, user_row_actions, editable_roles)
In the callback function for each hook I use wp_get_current_user() and perform a WP query to count the number of posts where the user id of the current user is stored as a meta value. I use this result to decide on the filter output/action performed (Complex task, cannot be changed).
As a result, when loading the users.php page, the WP Query seem to be executed in every hook callback function (which makes sense).
For performance reasons I would like to "nest" the hooks. In the "init" action hook, the WP query should be performed and the result should be passed to the following action hooks and filters. Two questions remain:
1) Is it necessary at all to care about performance here? Or does Wordpress have some internal "caching" mechanism that recognises identical queries and perform them only once when loading a page?
2a) The following example works for now, but I am not sure if this is safe to work with this in general. Question is: As my custom hook "myfuncs" is defined inside a hook (init), is it always known and can be hooked into, e.g. in functions.php or Plugin Code?
2b) Regarding the nested WP hooks (e.g. admin_head-users.php): are they executed normally according to their priority or may they be delayed/not executed at all sometimes as they are nested?
3) Is there a different solution/best practice?
add_action('init', 'initfunc', 1 );
add_action('myfuncs', 'myfuncs_callback', 1 );
public function initfunc() {
global $pagenow;
$args = (array) $pagenow; // only to simplify this example.
do_action( 'myfuncs', $args );
}
public function myfuncs_callback ($args) {
if($args[0] === "somevalue") {
add_action( 'admin_head-users.php', 'add_user_css' ,1 );
}
}
public function add_user_css () {
echo "<style>/*some styles*/</style>";
}