Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Excuse me, I'm very new to PHP and WordPress, but I'm trying to link to an exterenal js file called trans.js, that relies on jQuery. Here is the code at the beginning of the header.php:

  <script type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/trans.js"></script>

and here is the enqueue within the functions.php

function twentytwelve_scripts_styles() {
    global $wp_styles;

    wp_enqueue_style( 'twentytwelve-style', get_stylesheet_uri() );

}

add_action( 'wp_enqueue_scripts', 'twentytwelve_scripts_styles' );

function my_scripts_method() {
    wp_enqueue_script(
        'custom-script',
        get_stylesheet_directory_uri() . '/js/trans.js',
        array( 'jquery' )
    );
}

add_action( 'wp_enqueue_scripts', 'my_scripts_method' );

Yet it still does not link up with the trans.js — does anyone know why this is?

share|improve this question

2 Answers 2

You could use only one function to do all because it's the same hook wp_enqueue_scripts:

add_action( 'wp_enqueue_scripts', 'my_scripts_method' );
function my_scripts_method() {
   //global $wp_styles; //here no use unless you have to use it in a conditional stylesheet for example
   wp_enqueue_style( 'twentytwelve-style', get_stylesheet_uri() );
   wp_enqueue_script('custom-script', get_stylesheet_directory_uri() . '/js/trans.js',array( 'jquery'), null, false );
   );
}

It's no use modifying the header.php, actually it's better to handle scripts and stylesheets in functions.php (or in a plugin) than hard coding templates. The recommanded way is to enqueue your stylesheets and scripts because you get a better control (dependencies, load, etc).

share|improve this answer

If you place the below code snippet in your functions.php then, trans.js file should be available in the source. You don't need to change the code in header.php.

function my_scripts_method() {
    wp_enqueue_script(
        'custom-script',
        get_stylesheet_directory_uri() . '/js/trans.js',
        array( 'jquery' )
    );
}

add_action( 'wp_enqueue_scripts', 'my_scripts_method' );

Reference: http://codex.wordpress.org/Function_Reference/wp_enqueue_script#Link_a_Theme_Script_Which_Depends_on_jQuery

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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