Inserting JS snippet in the footer if there is no wp_footer?

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?

Related posts

Leave a Reply

2 comments

  1. If the theme does not implement wp_footer() a lot of functionality that depends on it will break. For this reason, implementing wp_footer() is required to get your theme accepted in the WP.org directory. So it is not unreasonable to break when wp_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 of wp_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 in wp_footer, and reading the result to see whether this control code can be found.

  2. You could use output buffering and append the script to the end. But you shouldn’t.

    1. It is slow.
    2. It is not safe. Some other plugin could run right before you do and compress everything to gzip. You would just invalidate the whole page in this case.
    3. The user may have removed 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.