Can I insert a <script> tag in a .php template?

[ad_1]

When I google this I get suggestions to install a code plugin- I did but it doesn’t seem to work. I think I’ve also seen suggestions to insert it in the wordpress header and then check conditionally if I’m on the page I want the script to run for. I’m more comfortable just inserting the script tag. Is that bad practice?

[ad_2]
4 Comments
  1. If you upgrade to the latest version of the template, your code will get overwritten.

    I use WP Code Snippets plugin if I need to add code somewhere.

    I use the [shorttags] and drop the shorttag in the page where I want the code to appear.

  2. Yes it is, pls do not touch the .php template file. Go for the simple Free Insert Header and Footer Code Plugin and stick it in there.

    Hope this helped!

  3. Use a child theme. Edit the header.php or footer.php files that way. Show us your code.

  4. If it is a template of a theme created by you then it is okay, if the theme is from the WordPress library or other sources that may launch updates, it can be overwritten in future updates so it is not a good idea.

    In any way, adding inline JavaScript code in your templates is not a good practice in WordPress development, so other developers that join your project may find confusing your approach since all the scripts should be in an individual folder of your theme. The correct way to do so is using the wp_enqueue_scripts hook and check if the page that is running is the one in which you want to add the script. In the end, if you still want to add the script tag in a template of your theme, you shouldn’t encounter any problem, it is just a developer convention to do it different in WordPress.

 

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