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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Better would it be to register an object on the window objects that holds your custom variables. window.myShortCodeValues = {'sLink' : '<?php echo do_shortcode( '[global_variable variable_name="LINKTEXT"]' ); ?>'}; 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.
Agree, that's what I'm getting at with the ViewBag. Happy to advocate your answer if you wish to post it.
Nah, you edited in the oViewBag as I wrote my comment, your answer is sufficient :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.