0

I'm working with Wordpress and my objective is to create a kind of main.js file to call instead of including in page my script. Being a plugin, I need to use some php variables and functions into it. Can I just write my .js like

<?php
        $dd = get_option('KleeiaDev_project_period');
        if(empty($dd)) $dd = 7; ?>
        var myDate=new Date();
        myDate.setDate(myDate.getDate()+<?php echo $dd; ?>);
        $(document).ready(function() {
        $('#ending').datepicker({
            showSecond: false,
            timeFormat: 'hh:mm:ss',
            currentText: '<?php _e('Now','KleeiaDev'); ?>',
            closeText: '<?php _e('Done','KleeiaDev'); ?>',
            ampm: false,
            dateFormat: 'dd-mm-yy',
            timeFormat: 'hh:mm tt',
            timeSuffix: '',
            maxDateTime: myDate,
            timeOnlyTitle: '<?php _e('Choose Time','KleeiaDev'); ?>',
            timeText: '<?php _e('Time','KleeiaDev'); ?>',
            hourText: '<?php _e('Hour','KleeiaDev'); ?>',
            minuteText: '<?php _e('Minute','KleeiaDev'); ?>',
            secondText: '<?php _e('Second','KleeiaDev'); ?>',
            timezoneText: '<?php _e('Time Zone','KleeiaDev'); ?>'
        });
    });

Or should I consider something? I mean is that possible? For now this piece of code and more is directly in my php plugin file. Thanks.

middlelady
  • 573
  • 2
  • 13
  • 36

1 Answers1

1

If you want to send php variables to an external js file you need to do something of the following:

Inside your .php file

<?php

// Variables
$var1 = "test1";
$var2 = "test2";

?>

// Include your js file
<script type="text/JavaScript" src="/js/main.js"></script>

// Send your php variables to js variables; this has shorthand php tags also.
<script type="text/javascript">
    var var1 = "<?= $var1 ?>";
    var var2 = "<?= $var2 ?>";
</script>

Then inside your js file you can call these variables:

main.js

$(document).ready(function() {
    alert(var1); //Alerts 'test1'
    alert(var2); //Alerts 'test2'
});
rnevius
  • 26,578
  • 10
  • 58
  • 86
Matt
  • 1,749
  • 2
  • 12
  • 26