1

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?

3 Answers 3

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' )
    )
);
1

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
    }
}
1

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);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.