Load jQuery in PHP page – no head tags

This is probably super simple answer, but I just can’t figure this out.

Basically, I’ve got a php page only starting with opening <?php tag.

Read More

I’ve got a jquery script that I need to call on this page.

<script type="text/javascript">
     $('input[name="_manage_item"]').click(function() {
     $('input[name="_item"]')[this.checked ? "show" : "hide"]();
     });
</script>

From what I researched, I need to load the script by placing

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

into the <head> tags of the page.

But my page doesn’t have the html <head> or <body> tags. Where do I call the script then ?

I tried to place it in front of the opening <?php tag, but that broke the page.

What is the correct way of doing this ?

Related posts

2 comments

  1. You can place your javascript outside the php tags at the bottom of you page. But when you use the php in a web page, you should add the html and head and body tags. A simple php page could look like this:

    <html>
    <head>
      <!-- stylesheets and javascript -->
    </head>
    <body>
      <?php
        //You php-code
      ?>
      <!-- scripts at the end of the page to let the side load faster -->
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
      <script type="text/javascript">
       $('input[name="_manage_item"]').click(function() {
         $('input[name="_item"]')[this.checked ? "show" : "hide"]();
       });
    </script>
    </body>
    </html>
    
  2. Relying on your wordpress tag, I suggest you to read this article. There are described all details concerning javascript usage within wordpress. Probably the most common way is to use wp_register_script() function.

    The safe and recommended method of adding JavaScript to a WordPress generated page, and WordPress Theme or Plugin, is by using wp_enqueue_script().

    I would also advise you to merge your code to a distinct file, and load it straight after jquery library. It is a good practice, because in such a way browser can cache your script and would not download it on every page request. You should also wrap it into a $( document ).ready() function, to be sure that it will be executed only only when document is in ready state.

Comments are closed.