Better alternative to wp_add_inline_script?

[ad_1]

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]
1 Comment
  1. 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`
    `};`

 

This site will teach you how to build a WordPress website for beginners. We will cover everything from installing WordPress to adding pages, posts, and images to your site. You will learn how to customize your site with themes and plugins, as well as how to market your site online.

Buy WordPress Transfer