I wrote a plugin which uses wp_enqueue_script()
which will include the snippet in either the header or footer depending on the parameters you pass it. The in_footer
parameter works great – if the theme utilizes the wp_footer()
hook.
What are my options if I want to include the JS snippet directly before the </body>
tag if a theme is not using wp_footer()
hook?
If the theme does not implement
wp_footer()
a lot of functionality that depends on it will break. For this reason, implementingwp_footer()
is required to get your theme accepted in the WP.org directory. So it is not unreasonable to break whenwp_footer()
is missing.Be sure to add a notice in your FAQ that you require
wp_footer()
in the theme. You can also add a check in your plugin admin page: checking for the existence ofwp_footer()
can be as simple as loading a page with a special$_GET
variable in the background, which will trigger a hook that outputs some control code inwp_footer
, and reading the result to see whether this control code can be found.You could use output buffering and append the script to the end. But you shouldnât.
wp_footer
intentionally.Aside:
</body>
, the closing tag, is optional. I havenât used it since 2001. So thatâs nothing you can rely on.