1

I have the following jQuery code in my Wordpress site, that waits for 0.8 seconds aften the button is clicked and before the site is redirected to the given URL written inside the window.location.

Wait before url is opened after button is clicked

$("#button").click(function() {

  setTimeout(function() {
    window.location = "https://www.w3schools.com";
  }, 800);

});

For adding the link text using the WP GUI I have installed the "Wordpress Custom Global Variables" plugin and fetches the link text like this in the front-page.php template file:

<button id="button"><?php echo do_shortcode( '[global_variable variable_name="LINKTEXT"]' ); ?></button>

Is there a way to somehow fetch the [global_variable variable_name="LINKURL"] in the window.location jQuery code, so that the link can be maintained from the GUI?

Fjott
  • 1,107
  • 3
  • 15
  • 38

1 Answers1

2

On the Wordpress page you could define the JS var like this.

<script type='text/javascript'>
    var sLink = '<?php echo do_shortcode( '[global_variable variable_name="LINKTEXT"]' ); ?>';
</script>

Then read it in your function:

$("#button").click(function() {
  setTimeout(function() {
    window.location = sLink;
  }, 800);
});

Note: You may have to use just sLink without the var if scoping is an issue. I would normally add these properties to an object called oViewBag or similar. Ensuring its defined in the correct scope.

atoms
  • 2,993
  • 2
  • 22
  • 43
  • 1
    Better would it be to register an object on the window objects that holds your custom variables. `window.myShortCodeValues = {'sLink' : ''};` so you can read it with `window.myShortCodeValues.sLink` and rest assured that not another script will overwrite your variable accidentally. and you can add other shortcode values too it as desired, all stored neatly under one object. – Tschallacka Jan 15 '19 at 12:35
  • 2
    Agree, that's what I'm getting at with the ViewBag. Happy to advocate your answer if you wish to post it. – atoms Jan 15 '19 at 12:39
  • 1
    Nah, you edited in the oViewBag as I wrote my comment, your answer is sufficient :-) – Tschallacka Jan 15 '19 at 12:45