Is there a way to push javascript or css ‘on-page’ in a template via functions.php

You can just hook into wp_head for CSS or JS, or wp_footer for JS (style tags need to be in the header):

function wpse_276403_output_scripts() {
    ?>
    <script>alert('Hello world!');</script>
    <style>
        body {
            background: #F00;
        }
    </style>
    <?php
}
add_action( 'wp_head', 'wpse_276403_output_scripts' );

function wpse_276403_output_scripts() {
    ?>
    <script>alert('Hello world!');</script>
    <?php
}
add_action( 'wp_footer', 'wpse_276403_output_scripts' );

If your script or style depends on a registered or enqueued script, you can use wp_add_inline_style() or wp_add_inline_script() to ensure that the JS/CSS is output after the script or style it depends on:

function wpse_276403_output_scripts() {
    wp_enqueue_script( 'my-dependency-script', '/uri/to/script/file.js' );
    wp_add_inline_script( 'my-dependency-script', 'alert("Hello world!");' );
    wp_enqueue_style( 'my-dependency-style', '/uri/to/stkle/file.css' );
    wp_add_inline_style( 'my-dependency-style', 'body { background: #F00; }' );
}
add_action( 'wp_enqueue_scripts', 'wpse_276403_inline_scripts' );

This way the scripts and styles will only be output if my-dependency-script/my-dependency-style have been loaded, and will load after them. Note that you don’t need to add the <script></script> or <style></style> tags.

Leave a Comment