0

I placed a javascript inside a .php file

$script = "<script type='text/javascript'>
        jQuery( document ).ready( function($) {         
            $(document).ready(function() {
              $('#particles').particleground({
                dotColor: '<?=json_encode($dotcolor)?>',
                lineColor: '#5cb9bd',                   
              });
            });
        }
     );
    </script>";

and tried to use <?=json_encode($dotcolor)?> to echo a variable. But it isn't working.

Any idea what I'm doing wrong?

1

This should work:

<?php $script = "<script type='text/javascript'>
        jQuery( document ).ready( function($) {         
            $(document).ready(function() {
              $('#particles').particleground({
                dotColor: " . json_encode($dotcolor) . ",
                lineColor: '#5cb9bd',                   
              });
            });
        }
     );
    </script>";
    ?>

Note: Its a better practice to enqueue Javascripts with wp_enqueue_script() and include dynamic strings via wp_localize_script().

Docs: https://codex.wordpress.org/Function_Reference/wp_enqueue_script https://codex.wordpress.org/Function_Reference/wp_localize_script

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.