Including Javascript options

For a WordPress Theme I know javascript files (ending in .js) must be included using wp_enqueue_script in functions.php but how do I include additional javascript code? For example, say I need to add this:

jQuery(function($){
    jQuery.supersized({
        slides:
        [
             'http://google.com',
             'http://google.co.uk'
        ]
    });
});

Where would I put this? Do I put it within <script> tags in the header.php?

Related posts

Leave a Reply

3 comments

  1. Use wp_localize_script to pass data from php to your javascript:

    wp_register_script(
        'wpa_script',
        get_template_directory_uri() . '/js/script.js',
        array('jquery'),
        null,
        false
    );
    
    wp_localize_script(
        'wpa_script',
        'WPAData',
        array(
            'slides' => array( 'http://google.com', 'http://google.co.uk' )
        )
    );
    
  2. Just put it inside a callback, hooked into the correct action:

    add_action( 'wp_print_scripts', 'wpse88383_print_scripts' );
    
    function wpse88383_print_scripts() {
        if ( ! is_admin() ) {
            ?>
                <script type="text/javascript">
                    jQuery(function($){
                        jQuery.supersized({
                            slides:
                            [
                            'http://google.com',
                            'http://google.co.uk'
                            ]
                        });
                    });
                </script>
            <?php
        }
    }
    
  3. Since WP 4.5 the correct way to do this is to use wp_add_inline_script. This function preprends or appends your script to an enqueued script. For instance, you could append your script to jquery like this:

    $script = 'jQuery(function($){
      jQuery.supersized({
        slides:
        [
             "http://google.com",
             "http://google.co.uk"
        ]
      });
      });';
    wp_add_inline_script ('jquery', $script);