0

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'

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

3 Comments

so I can include the php code directly in the page ?
Right, f.e. <?php $arar = array( 30,50,10,1,-10 ); $amon = $arar[array_rand($arar, 1)]; ?> and after that html part : <div class="promo-code"></div> [mycred_link amount=$amon href="https://example.org/choose-card/" ]Collect the prize[/mycred_link] </div>
Actually you can add the code to the current page template, or add it as part of you button short code place (in functions.php) . Or you can add the php code directly to page/post content with "Insert PHP" plugin: [link]hostinger.com/tutorials/wordpress/…

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.