domain90
domain90

Reputation: 109

Jquery not working in Wordpress; function php

Im trying to add my script into my wordpress function.php file.

So far I have this:

<?php
function add_google_jquery() {
   if ( !is_admin() ) {
    wp_deregister_script('jquery');
    wp_register_script('jquery',   ("https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"), false);
    wp_enqueue_script('jquery');
  }
}
add_action('wp_enqueue_script', 'add_google_jquery');

function menu_bar(){
?>
<script type="text/javascript">
    $(document).ready(function() {
        var navbar = $(".navbar");

        $(window).scroll(function(){
            if(navbar.scrollTop() == 0){
              navbar.css("background", rgba(0,0,0,0));
            }
            else 
            {
              navbar.css("background", rgba(255,255,255,0));
            }
        });
    });
</script>
<?php
}
add_action( 'wp_footer', 'menu_bar');
?>

I had already tried using jQuery instead of $ and declaring $ = jQuery.

Upvotes: 0

Views: 652

Answers (1)

jdp
jdp

Reputation: 366

According to the Developer Reference, you should add a dependency to json2 when you enqueue your add_google_query(). I don't think you need to run the wp_register_script() if you enqueue it as such (after you've de-registered the core version of jQuery):

wp_enqueue_script('jquery',"https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js", array("json2"));

I agree with @Random above that you should put the js in a separate file and call it via wp_enqueue_script() via an add_action on the get_header hook and put true in to load in the footer as such if you want the script to run in every template:

function add_my_menu_bar() { wp_enqueue_script('my_menu_bar',"path-to-the-js-file.js", array("jquery"), false, true); } add_action('get_header','add_my_menu_bar');

Good coding practice with jQuery and WordPress is not to use $ to identify a jQuery object. Recommend you get used to it. I generally write my jQuery dependent scripts using $ and then find/replace all with jQuery.

As a last point, I strongly recommend you do not edit the core functions.php file in wp-includes. That file will likely be overwritten in future WordPress version changes. Most, if not all, themes will have a functions.php file that will be included when the theme runs. That's a better place to put your functions and action hooks.

Upvotes: 1

Related Questions