简体   繁体   中英

How to use javascript variable in a shortcode?

I made a simple Scratch Card game, but I have a problem with some code section. How do I use a javascript variable in a WordPress shortcode?

First i use a random number to define the prize amount.


<script>
var arar = [1,2,3,4,5]
selectG = arar[Math.floor(Math.random() * arar.length)];
if (selectG == 1) {
    var amon = 30;
  } else if (selectG == 2) {
    var amon = 50;
  } else if (selectG == 3) {
    var amon = 10;
  } else if (selectG == 4){
    var amon = 1;
  } else {
    var amon = -10;
} 
</script>

Then i pass the amount as "amon" in the shortcode

<div class="promo-code"></div>
  [mycred_link amount=amon href="https://example.org/choose-card/" ]Collect the prize[/mycred_link]
</div>

When the button "Collect the prize" is pressed it adds the amount to the user points balance (they are used on site to pay for privileges on the website). However it always add 10 points, no matter what.

I researched it (the plugin is called MyCred) and I found out 10 is the default value to add if the amount is undifined or it returns an error (let's say we pass it a random text like> amount = sdfsdfsdf - it will still add 10 points). If I use an integer it will work adding the amount specified...but I need the amount to by changed by the random value selected from the array 'arar'

WordPress shortcode runs at the server side, so you cannot pass js variable into the code. But you can generate same random value in php:

$arar = array(
    30,50,10,1,-10
);
$amon = $arar[array_rand($arar, 1)];

and use the result here:

<div class="promo-code"></div>
  [mycred_link amount=$amon href="https://example.org/choose-card/" ]Collect the prize[/mycred_link]
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM