How to capture URL params within wordpress and pass along in javascript

61 Views Asked by At

My lack of experience with both Wordpress and Javascript is tripping me up.

I have a Wordpress page that has a Jotform embedded using this tag:

<script type="text/javascript" src="https://form.jotform.com/jsform/FORMCODE"></script>

But I have a value coming into my Wordpress through the URL that I need to pass along in the embedded Jotform's URL. I cannot figure out how to do that. Do I want to use PHP? Javascript?

I tried this, which didn't work at all:

<script type="text/javascript"> 
function getURL(){
    let paramString = urlString.split('?')[1];
    let params_arr = paramString.split('&');
    let pair = params_arr[0].split('=');
    return "https://form.jotform.com/jsform/230391120310032?coursecode=" + pair[1];
}
</script>
<script type="text/javascript" src="getURL();"></script>

Thanks for any help!

1

There are 1 best solutions below

2
Wisdom Ighofose On

To add a javascript code to a WordPress page you need the page id else the js code will be on all the pages.

You can either add the js code to the head of the page likes so:

add_action('wp_head',function () {
  // 10 is the page id; 
  if (is_page ('10')) { 
    ?>
  <script type="text/javascript">
    function getURL(){
    let paramString = urlString.split('?')[1];
    let params_arr = paramString.split('&');
    let pair = params_arr[0].split('=');
    return "https://form.jotform.com/jsform/230391120310032?coursecode=" + pair[1];
}
 </script>
  <script type="text/javascript" src="getURL();"></script>
    <?php
  }
}
 );

Then put the js code on the footer like so:

add_action('wp_footer',function () {
  // 10 is the page id; 
  if (is_page ('10')) { 
    ?>
  <script type="text/javascript">
    function getURL(){
    let paramString = urlString.split('?')[1];
    let params_arr = paramString.split('&');
    let pair = params_arr[0].split('=');
    return "https://form.jotform.com/jsform/230391120310032?coursecode=" + pair[1];
}
 </script>
  <script type="text/javascript" src="getURL();"></script>
    <?php
  }
}
 );

Whichever snippet you pick should be added to your theme functions.php or code snippet plugin if you have one