WordPress WordPress Theme Development Working with CSS and JS in WordPress Themes How to Link to JS from functions.php File

Struggling to insert js in functions.php in the right way to get it working properly on my site

Hi all, So I am just starting to learn how to convert static templates over and my first attempt is not going so well :P.

I've managed to insert the css fine, but I'm struggling with the js. I'm using "Owl Carousel" and in my static template there are two files for owl but in my js folder there are lots more. Do I assume that the owl files listed in my template are dependent on all these others and therefore I need to include them in the dependency part of the wp_enqueue_script? Or do I not need to worry and the template will find what it needs? My thinking is the former.

Also, I have some js included on my main static template page that, from the video, looks like it needs to go into the app.js file. Can someone please confirm this is correct or not? Basically, I'm not seeing the code appear and my navigation is not functioning as it should so clearly I'm doing something wrong. Not sure how to show code on here, but I'll try and paste it below.

This is app.js file

$(document).foundation(); 
    $('.owl-carousel').owlCarousel({
      loop: true,
      margin: 10,
      nav:true,
      dots:true,
      autoplay:true,
      autoplayTimeout:8000,
      autoplayHoverPause:true,
        responsiveClass: true,
        responsive: {
          0: {
            items: 1,
            nav: true
          },
          600: {
            items: 1,
            nav: true
          },
          1000: {
            items: 2,
            nav: true,
            loop: true,
            margin: 20
          }
        }
      }); 

  // Slideshow
  var slideIndex = 1;
  showDivs(slideIndex);

  function plusDivs(n) {
    showDivs(slideIndex += n);
  }

  function currentDiv(n) {
    showDivs(slideIndex = n);
  }

  function showDivs(n) {
    var i;
    var x = document.getElementsByClassName("mySlides");
    var dots = document.getElementsByClassName("demodots");
    if (n > x.length) {slideIndex = 1;}    
    if (n < 1) {slideIndex = x.length;}
    for (i = 0; i < x.length; i++) {
       x[i].style.display = "none";  
    }
    for (i = 0; i < dots.length; i++) {
       dots[i].className = dots[i].className.replace(" w3-white", "");
    }
    x[slideIndex-1].style.display = "block";  
    dots[slideIndex-1].className += " w3-white";
  }

    $( ".nav-toggle" ).click(function() {
      $(this).toggleClass("open");
      $("nav").fadeToggle(100);

      return false;
    });

This is my functions.php file

<?php 

function poog_theme_styles(){
  wp_enqueue_style('foundation_css',get_template_directory_uri() .'/css/foundation.css');
  wp_enqueue_style('normalize_css',get_template_directory_uri() .'/css/normalize.css');
  wp_enqueue_style('w3c_css','https://www.w3schools.com/w3css/4/w3.css');
  wp_enqueue_style('lobster_css','https://fonts.googleapis.com/css?family=Lobster');
  wp_enqueue_style('theme_red_css',get_template_directory_uri() .'/css/theme-red.css');
  wp_enqueue_style('owl_carousel_css',get_template_directory_uri() .'/css/owl.carousel.min.css');
  wp_enqueue_style('owl_theme_css',get_template_directory_uri() .'/css/owl.theme.default.min.css');
}
add_action('wp_enqueue_scripts','poog_theme_styles');

function poog_theme_scripts(){
  wp_enqueue_script('font_awesome_js',get_template_directory_uri() . '/js/fontawesome-all.min.js',array('jquery'),'',false);
  wp_enqueue_script('foundation_js',get_template_directory_uri() . '/js/foundation.min.js', array('jquery'),'',true);
  wp_enqueue_script('owl_carousel_js',get_template_directory_uri() . '/js/owl.carousel.js', array('jquery','owl.animate.js','owl.autoheight.js'),'',true);
  wp_enqueue_script('main_js',get_template_directory_uri() . '/js/scripts.js', array('jquery'),'',true);
}
add_action('wp_enqueue_scripts','poog_theme_scripts');

?>

I'm finding this really tough and spent many hours on it. I certainly don't want to throw in the towel so I could use your genius help :). Thank you Andy

6 Answers

Konrad Traczyk
Konrad Traczyk
22,281 Points

Hello Andy,

Basic problem here is, that you're missing attached owl carousel dependencies. In other words you have to use wp_enqueue_script on 'owl.animate.js','owl.autoheight.js' to use them in dependencies parameter, also i haven't seen your app.js file linked through wp_enqueue_script.

<?php
function poog_theme_scripts(){
    wp_enqueue_script('font_awesome_js',get_template_directory_uri() . '/js/fontawesome-all.min.js',array('jquery'),'',false);
    wp_enqueue_script('foundation_js',get_template_directory_uri() . '/js/foundation.min.js', array('jquery'),'',true);
    wp_enqueue_script('owl.autoheight.js',get_template_directory_uri() . '/js/owl.autoheight.js', array('jquery'),'',true);
    wp_enqueue_script('owl.animate.js',get_template_directory_uri() . '/js/owl.carousel.js', array('jquery'),'',true)
    wp_enqueue_script('owl_carousel_js',get_template_directory_uri() . '/js/owl.animate.js', array('jquery','owl.animate.js','owl.autoheight.js'),'',true);
    wp_enqueue_script('main_js',get_template_directory_uri() . '/js/scripts.js', array('jquery', 'owl_carousel_js'),'',true);
}
add_action('wp_enqueue_scripts','poog_theme_scripts');

You're saying that that you have some js linked by script tag in your static template, which is bad way to do this, you should've use wordpress conditional functions to link additional script/style files. Checkout how im linking google maps script on my project which is used it only on contact page.

<?php
function wpdocs_theme_name_scripts() {
    wp_deregister_script('wp-embed');

    if(is_page('contact')){
        wp_enqueue_script('maps', 'http://maps.googleapis.com/maps/api/js?key=my_key', array(), '1.0.0', true);
    }

    wp_enqueue_style('style-name', get_stylesheet_uri());
    wp_enqueue_style('font-awesome', "https://use.fontawesome.com/releases/v5.0.10/css/all.css");
    wp_enqueue_script('script-name', get_template_directory_uri() . '/js/scripts.min.js', array('jquery'), '1.0.0', true);
}
add_action('wp_enqueue_scripts', 'wpdocs_theme_name_scripts');

I've combined all js/css files by grunt for every project that's why i have only few files here.

I prefer slick slider over owl carousel, so i won't check your js to be correct.

Hopes it helps,

Konrad

Hi Konrad, Thanks for your reply. Indeed I had forgotten to include the app.js file, although adding it in has made no difference.

Regarding the owl carousel. If you look at my static site homepage here www.pageoneofgoogle.co.uk you will see when you inspect the page, what I mean regarding inline scripts and owl carousel. There is only one script entry for owl and yet in my js folder there are around 8 other scripts that I think are dependent on owl.carousel.js in order for things to work. So do I only need to reference my main owl js file in wp_enqueue_script or do I need to include all of the 8? That's one place I'm getting confused.

The other is my static scripts to manage dropdown navigation and main image slider. The reason they are not in a separate scripts.js file is that every time I tried to include them in that file, they wouldn't function so I left them inline. Now, when I try to put them in app.js (following the video lesson), they don't show up on my page and the nav menu doesn't work still.

Now I'm not even sure that app.js is a necessary file for including inline scripts or whether it's just a template related file from the template being used in the lesson.

I will have a look at slick slider, but in the short term, I just need to get my files working.

Thanks again for the support. Andy

Konrad Traczyk
Konrad Traczyk
22,281 Points

You should've include all your *.js files by wp_enqueue_script, or merge them in one file in your prefered way.

I think you should try avoid inline scripting at all, the only scripts you should've inline is google stuff(tag manager, adsense, etc.) and some tracking, advertisements scripts. Also order of your files matters, you should've look into console in devtools.

Site that you have posted has one error in console, what can lead to unexpected results.

Thank you Konrad for your support. I have tried merging the js code into my main.js but as I mentioned, it just breaks things and I'm not clued up on js to be able to problem solve it. So for the moment it has to stay on the page.

That however, would not fix the fact that I still can't seem to enqueue the files properly. I have followed the tutorial as correctly as I can. I suspect with my limited knowledge that it is due to either Wordpress delivering a jQuery version that is different to my template; and/or it could be that I'm not sure how to set Owl Carousel js files up properly; and/or I am coding the onpage/inline js incorrectly.

I am a student and novice in Wordpress and JS and so I suspect I need more direct support as "i don't know what I don't know". Thanks again for your advice. I have message TeamTreeHouse directly and asked for support. Two weeks and a "promise of support" later and I'm still waiting for a response!

Alena Holligan
STAFF
Alena Holligan
Treehouse Teacher

Let's start with one issue at a time, so first let's address the navigation.

The scripts.js file from your original site seems to include your navigation jquery.

  1. You have included scripts.js as dependent on jquery and loading in the footer. Do you see that file attached when you view the site?
  2. You cannot use jquery directly, you need a wrapper, have you changed your function calls to be wrapped as follows
jQuery( document ).ready( function( $ ) {
    // $() will work as an alias for jQuery() inside of this function
    [ your code goes here ]
} );

Example would be

jQuery( document ).ready( function( $ ) {
    //Navigation menu
   $(document).ready(function() {
      $("#navToggle a").click(function(e){
            e.preventDefault();

        $("header > nav").slideToggle();
        $("#logo").toggleClass("menuUp menuDown");
       });

        $(window).resize(function() {
            if($( window ).width() >= "900") {
                $("header > nav").css("display", "block");

                if($("#logo").attr('class') == "menuDown") {
                    $("#logo").toggleClass("menuUp menuDown");
                }
            }
            else {
                $("header > nav").css("display", "none");
            }
        }); 

        $("header > nav > ul > li > a").click(function(e) {
            if($( window ).width() <= "900") { 
                if($(this).siblings().size() > 0 ) {
                e.preventDefault();
                $(this).siblings().slideToggle("fast")
                }
            }
        }); 

} );

Hello Alina,

I do see the scripts.js file listed at the footer and if I open it up in the sources panel all the code shows up fine. I had also used the wrapper you mentioned previously, but it made no difference so I took it out. I've just added it back in but it still makes no difference.

I get that it makes it harder to support me because i'm developing it offline, but I like to think I'm not an idiot and can follow the videos quite well. My problem I think is that I'm starting with a more complex template than the one in the video and it uses OWL Carousel and I'm struggling to understand what files need to be included and what ones are dependencies etc.

At the moment, I can't even get the mobile nav menu to work. If you look at www.pageoneofgoogle.co.uk on a mobile device, you'll see what it should look like. On the wordpress version it's just a list of links.

Alena Holligan
Alena Holligan
Treehouse Teacher

part of it, you are missing the closing for the jquery wrapper

});

Hi Alena,

I do use Chrome inspector and I am aware that there are some errors in the js code. These errors have also been present on the static version of the site which seems to operate ok. I haven't learned JS yet so correcting these errors is a whole other thing to fix.

You asked for a user account, which I have set up, but as of yet I've not sent you the details. Can I send these to you somewhere so you can take a look just at my enqueue scripts to see if I'm getting the basics right?

You mention using the debugger to check the JS and CSS. I can see the errors in the JS but what's wrong with the CSS that would break the site?

Ok, in order to try and make things a bit easier to work out (probably not by much :P), I have installed wordpress and my theme so far on a test server. It's located at www.websitetestserver.co.uk.

Alena Holligan
Alena Holligan
Treehouse Teacher

doesn't help unless I can get in and see the code. if you can set up a user for me somewhere I can login to wordpress and check it out

Ah right, didn't think about that. I've set up a user account for you. How can I get the details to you as I don't want to post them in here. Thanks.