Linking php and javascript error in wordpress

I have got a javascript(jquery) file called custom.js in which i am using:

(function ($) {
    $(document).ready(function () {
        $('.days').countdown({
            until: directorDate,
            layout: '{dn} {dl}',
            timezone: +7
        });
        $('#weather').openWeather({
            city: 'directorCity //The city is in a string.It used to be 'New York,US'
            placeTarget: '.weather-place',
            iconTarget: '.weather-icon',
            customIcons: 'dark/files/img/icons/weather/'
        });
        });
})(jQuery);

In my header i am using:

Read More
<script>var directorDate = new Date(<?php $date = get_option('director_date');?>
<?php if( $date) : ?>
<?php echo $date; ?>
<?php endif; ?>);
var directorCity = <?php $city = get_option('director_city');?>
<?php if( $city) : ?>
<?php echo $city; ?>
<?php endif; ?></script>

Basically what is happening is that the header gets the data from a file themeoptions.php (A form in the wordpress admin for a user to input data.I have not shown it because the structure of both director_city and director_date is the same there) and then custom.js gets the data from the header.

Now the countdown runs however the city is not displayed. Why is that so?

Related posts

Leave a Reply

3 comments

  1. You should probably echo the value instead of assigning it to a php variable like so:

    var directorCity = <?php echo $get_option('director_city');?>
    

    EDIT: It’s not entirely sure to me what you are trying to accomplish, you could perhaps try the following for tbe head:

    <script>
    var directorDate = new Date(<?php echo get_option('director_date');?>
    var directorCity = <?php echo get_option('director_city');?>
    </script>
    
  2. If your site is no longer working there is probably a error in your php. Please post your code here.

    This sort of thing is best done using wp_localize_script, but if you want to output it directly try something like this, think it’s a bit more readable than the other answers:

    //use ternary operator to check, otherwise we want an empty string
    $director_date = get_option('director_date') ? get_option('director_date') : '';
    $director_city = get_option('director_city') ? get_option('director_city') : '';
    
    ?>
    
    <script>
        var directorCity = <?php echo $director_city; ?> ;
        var directorDate = <?php echo $director_date; ?> ;
    </script>
    

    Also I don’t know if it’s just a typing error in the code here or is actually in your javascript but in your options for openWeather you are passing

    city: 'directorCity'
    

    rather than

    city: directorCity