Lately I’ve been finding myself following a pattern where I’m adding JS specific to certain PHP files (example, a JS function that only needs to run on the homepage gets added to `front-page.php`, etc) via `wp_add_inline_script`.
This works well, but it feels like an anti-pattern. Especially since I end up with a file that mixes HTML, JS, and PHP. It just doesn’t feel very clean.
But I don’t necessarily want to enqueue separate script files because I don’t want the browser to deal with downloading additional requests (unless I’m misunderstanding the performance hit)
Is there a better, more “WordPressy” way to achieve what I’m trying to achieve?
[ad_2]
Wrap these in if (is_page()) { … } functions
You can if is page / category / template / has URL parameter – all sorts.
`add_action(‘wp_head’, ‘your_function_name’);`
`function your_function_name(){`
`?>`
`PASTE HEADER CODE HERE in <script tags> if it’s script.`
`<?php`
`};`
`add_action(‘wp_footer’, ‘your_function_name’);`
`function your_function_name(){`
`?>`
`PASTE FOOTER CODE HERE in <script tags> if it’s script.`
`<?php`
`};`