Search code examples
javascriptphploopsrepeatshortcode

how to shorten a repetitive javascript php code


I am new to javascript. Please help with the following. I have a repetitive block of code that is about 40 "cases" of almost same code - which takes the returned value of wordpress do_shortcode and save to javascript variable (this part works fine).

I'd like to shorten it by some sort of a loop of code that achieved the same functionality. I try not to use COOKIE to pass value to PHP. Please see sample 1st few lines:

switch (id) {
case 1: oh = `<?php echo do_shortcode("[block id=\"oh1\"]"); ?>`;break;
case 2: oh = `<?php echo do_shortcode("[block id=\"oh2\"]"); ?>`;break;
case 3: oh = `<?php echo do_shortcode("[block id=\"oh3\"]"); ?>`;break;
case 4: oh = `<?php echo do_shortcode("[block id=\"oh4\"]"); ?>`;break;`
...
}

jQuery('#id').html(oh);

I have to specify 40 lines like above and have not found another way. Please share your valuable idea. THANKS


Solution

  • What about this (I assume your switch is in Javascript).

    oh = '<?php echo do_shortcode("[block id=\"oh_num\"]"); ?>'.replace('_num', yourVariableInSwitch) ;break;`
    

    In this case you don't even need switch statement.

    If you have to do if 40 times:

    for (var i = 0; i < 40; i++) {
        console.log('<?php echo do_shortcode("[block id=\"oh_num\"]"); ?>'.replace('_num', i);
    }
    

    Render switch case statements for javascript with PHP

    switch (yourVariable) {
    <?php
    for ($i = 1; $i < 41; $i++) {
        print 'case ' . $i . ': oh = ' . do_shortcode("[block id=oh'" . $i . "']") . '; break;';
    }
    ?>
    }