• Hi there,

    I’ve recently started getting to know theme development with Sage, and it’s awesome! In the past, I’ve created a few themes from scratch or using Underscores base theme.

    One thing feels like a blank-spot in my self-education. I always have a really hard time implementing Javascript/jQuery dynamically. Whether it’s menu’s, or filtering a masonry sorted custom post type in a sexy way: sometimes I wrestle the code and end up winning, but often the code is really messy and I’m not that satisfied, although I got it working. But more often, I end up giving up, not understanding what is actually asked to incorporate this JS dynamically.

    So, this is a pretty broad question, but does anyone have any tips on how to become better in integrating JS dynamically (in WordPress theme development)?

Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator bcworkz

    (@bcworkz)

    It depends on how much is dynamic. For brief snippets, you can likely get away with simply outputting your JS inside of <script> tags using PHP like any other page content.

    If the dynamic portion is simply specific values assigned to variables, the proper way to pass these from PHP to JS is with wp_localize_script(). This was meant for passing internationalized formats, but it works for any value passed to a variable.

    For extensive dynamic JS, your external JS file can actually be a PHP page. You would enqueue it like any other external JS file, but it would have a .php extension so the server will process the PHP. As long as the resulting <link> tag has the correct MIME type attribute, it does not matter what the file extension is as far as the browser is concerned.

    For extensive dynamic JS, your external JS file can actually be a PHP page. You would enqueue it like any other external JS file, but it would have a .php extension so the server will process the PHP. As long as the resulting <link> tag has the correct MIME type attribute, it does not matter what the file extension is as far as the browser is concerned.

    interesting, could you point to a working example?

    I tried this but could not get it to work. I also found an alternative and similar approach which enqueues wp-ajax.php with url attributes to retrieve the js code, but that too didn’t work.

    I found a solution to my problem, which I share below. However, before I go into the solution, here is short bg on what my issue was. I have a page where I load js script to prefill a form with values previously saved as draft submissions into a bg post. I don’t have direct control on the form code printout so I need to do it with javascript.

    The javascript itself needs to be dynamically built depending on the form fields present on the form, ie I need to be able to solve this for any form. So the cut a long story short, I have both dynamic javascript as well as dynamic data that needs to be queued into the page.

    Till now I was printing an inline script code along with a json data object embeded in the script, and I chose to embed the json data object because the data is extensive and an ajax would require reloading a lot of data/objects into memory along with DB calls, not efficient. So building the data at the same time as the page is much faster.

    The problem with the above is that browser caching can leave the form filled with old data when a recent draft was saved and the page reloaded.

    So after trying multiple different routes which didn’t work for me, I finally did the following,

    1. Enqueue
      wp_enqueue_script('plugin-handle', 'file-path',...)
      a general global function which returns a localized data associated with the script handle.

      $.fn.post2CF7FormData = function(nonce){
            if( 0=== $(this).closest('#'+nonce).length ){
              return '';
            }
            if( 'undefined' != typeof window[nonce] ){
              return window[nonce];
            }
            return '';
         }
    2. localize the data that goes with it,
      wp_localize_script('plugin-handle', $nonce, $form_values);
      I use a wp nonce to uniquely identify the form values because potentially the page could have multiple forms with each requiring different data, therefore allowing me to localize multiple data sets on the same handle.
    3. inline the form filling code,
      ...
      var data = $form.post2CF7FormData(nonce);
      //carry on with the rest of the code...
      

    I am not bothered if the form code is cached as the code matches the cached form as well.

    Hope this helps someone else out there.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Integrating Javascript Dynamically in PHP’ is closed to new replies.