0

All I'm trying to do is add some javascript to a WordPress theme I'm making.

My functions.php file looks like this:

function my_scripts() {
    wp_enqueue_script( 'jquery' );

    wp_register_script( 'parallax', get_template_directory_uri() . '/parallax.js', array( 'jquery' ), NULL, true );
    wp_enqueue_script( 'parallax' );
}

add_action( 'wp_enqueue_scripts', 'my_scripts' );

And right before the closing tag of my header.php file is:

<?php wp_head(); ?>

Yet when I view my website, the only thing that happens is that my functions.php text is literally added to the VERY TOP of the page source (when you inspect the page's source you just see the text inserted before the tag).

Any assistance would be GREATLY appreciated. I didn't realize I had to jump through so many hoops to add JavaScript to a WordPress theme....

1

You need to wrap your text with <?php and ?>.

Like this:

<?php

function my_scripts() {
    wp_enqueue_script( 'jquery' );

    wp_register_script( 'parallax', get_template_directory_uri() . '/parallax.js', array( 'jquery' ), NULL, true );
    wp_enqueue_script( 'parallax' );
}

add_action( 'wp_enqueue_scripts', 'my_scripts' );

?>

Otherwise, the PHP parser never sees it - and it's sent as text to the browser.

I know some of this seems like hoops. It does at the start, believe me. But once you get how it works, and continue to learn more, it starts to make so much sense. I can tell you that from experience!

So, thank you for learning how to add scripts the WordPress way, rather than just adding <script> tags everywhere :) You'll thank yourself too if you use caching or minifying plugins later on, or need to fight with script dependencies.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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