Hook that's called on every moodle page

Hook that's called on every moodle page

by Ismail El -
Number of replies: 4

Is there any way to call a plugin function on basically every single moodle page? The after_config only seems to work in the admin, or in a weird way that $USER->id returns 0 even when a user logged in (it could be due to a cron event calling that). Something that's called regardless of the subfolder (/course, /my, admin, /, etc). WP has `init` or `plugins_loaded` for example which does what I am describing here.

If that's not possible, then is there a hook to listen for a successful login form submission, and another hook for the log out action?

Average of ratings: -
In reply to Ismail El

Re: Hook that's called on every moodle page

by Andreas Grabs -
Picture of Core developers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers Picture of Translators
Hi Ismail,

have look at the hook function:

<your-component>_after_config()
This function must be in your lib.php

Best regards
Andreas
Average of ratings: Useful (1)
In reply to Andreas Grabs

Re: Hook that's called on every moodle page

by Brad Simpson -
Note that hook_after_config() is only for Moodle 3.8+.

In a local plugin in our Moodle 3.4 site, I used hook_before_http_headers() to add a body class to every page.
Average of ratings: Useful (2)
In reply to Ismail El

Re: Hook that's called on every moodle page

by Ismail El -
I figured the issue was the $USER super-global was not reliable in that hook, and isloggedin() function on the other hand works for detecting the session status.
so use `$logged_in = isloggedin();` instead of `$logged_in = $USER->id > 0;`
In reply to Ismail El

Re: Hook that's called on every moodle page

by Mark Sharp -
Picture of Core developers Picture of Particularly helpful Moodlers Picture of Plugin developers
There is the `page_init` callback, but this can't be used in local plugins. But you could use `extend_navigation`, and though it's primary use is to extend navigation, by this time all the relevant global settings have been initialised ($PAGE, $USER etc)

  1. In your plugin add a lib.php file.
  2. Assuming your plugin is a local plugin called myplugin, create the function local_myplugin_extend_navigation(global_navigation $nav)
  3. Do your stuff. You don't actually have to do anything with the navigation.

There's a bit about this in the /local/readme.txt file.

Don't use this if you're intending to output html.

If you want to catch events, then you need event observers: https://moodledev.io/general/development/policies/component-communication#event-observers. To view the list of events available go to /report/eventlist/index.php

Average of ratings: Useful (2)