Wordpress causing Jquery to malfunction; PHP function not executing

Looking to incorporate a script into my WordPress function.php file.

Here's what I have so far:

<?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 attempted using jQuery instead of $ and defining $ = jQuery, but it didn't work as expected.

Answer №1

As mentioned in the Developer Reference, it is recommended to include a dependency on json2 when enqueuing the add_google_query() function. It may not be necessary to use wp_register_script() if you enqueue it like this (after deregistering 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 concur with @Random's suggestion to place the JavaScript code in a separate file and load it using wp_enqueue_script() within an add_action hooked into get_header, specifying 'true' to load it in the footer for universal usage in all templates:

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

When working with jQuery in WordPress, it is best practice not to use '$' as an identifier for jQuery objects. I recommend getting accustomed to this approach. Personally, I write my scripts with '$' and then replace all instances with 'jQuery'.

Lastly, I advise against editing the core functions.php file located in wp-includes. This file is likely to be overwritten during future WordPress updates. Most themes have their own functions.php file which is automatically included when the theme is activated, providing a safer location for adding your custom functions and action hooks.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve the object filtered by a specific group from an array of data

I have a data object that contains various groups and rules within each group item. My task is to filter the rules based on a search query, while also displaying the group name associated with the filtered rule. { "id": "rulesCompany", "group": [ ...

The AngularJS ng-repeat filter boasts dual parameters that vary based on the scope implemented

Two different instances of the same filter are causing unexpected outputs in my ng-repeat display. One instance is scoped at the app level and defined in the module, while the other is scoped at the controller level. Interestingly, when using the filter f ...

Managing touch devices and animations when hovering

Is there a way to remove or prevent all hover effects on a touch device? I've tried various scripts, but none seem to work for me. How can I test it with dev tools? I attempted this script but received an error: Cannot read property 'addEventList ...

Is Window.navigator malfunctioning on different browsers in Mac OS?

I'm attempting to access the navigator function in my project to share a specific URL, but I'm facing difficulties accessing it on Mac OS when using browsers other than Safari. Is there a solution to this issue? Below is the function I created f ...

Creating interactive JSON objects through the use of JavaScript and AngularJS

When using AngularJS to build a dynamic JSON from server data, I encountered an issue where my current declaration only works if the server data contains one item in the object array. How can I modify this to handle multiple items dynamically? $scope.it ...

Building a single page web application using TypeScript and webpack - a step-by-step guide

For a while now, I've been working on single page applications using Angular. However, I'm interested in creating a single page application without utilizing the entire framework. My goal is to have just one .html file and one javascript file, w ...

Struggling to implement nested routes with react-router-dom version 5.2.0?

I'm currently working on implementing nested routing in React using react-router-dom 5.2.0. For a better understanding of the project, you can access the CodeSandbox link here: https://codesandbox.io/s/nested-routes-8c7wq?file=/src/App.js Let's ...

Changing the background color of the canvas using Javascript

I want to create a rect on a canvas with a slightly transparent background, but I don't want the drawn rect to have any background. Here is an example of what I'm looking for: https://i.stack.imgur.com/axtcE.png The code I am using is as follo ...

What's the best method for uploading a file to AWS S3: POST or PUT requests?

Could you please provide insights on the advantages and disadvantages of utilizing POST versus PUT requests for uploading a file to Amazon Web Services S3? Although I have come across some relevant discussions on platforms like StackOverflow, such as this ...

How can we avoid excessive re-rendering of a child component in React when making changes to the parent's state?

In my React application, I am facing a situation where a parent component controls a state variable and sends it to a child component. The child component utilizes this state in its useEffect hook and at times modifies the parent's state. As a result, ...

Exploring the Wonderful World of Styled Components

I have a query regarding styled components and how they interact when one is referenced within another. While I've looked at the official documentation with the Link example, I'm still unclear on the exact behavior when one styled component refe ...

Searching in Seblod on Fields with No Content (Exact Matching)

Currently, I am working on a List & Search Type form with only one input field labeled Username. The form is set to Exact matching, meaning it should only return results if an exact match is found. However, when the Username field is left empty and I clic ...

Can you explain how to invoke a class with express().use function?

Currently, I am delving into learning Node JS with TypeScript but have hit a roadblock with a particular issue. In my app.ts file, I have initialized the express and attempted to call the router class inside the app.use() method, only to encounter an error ...

Show off beautiful text using a styled pre component in a React application

I've been attempting to highlight specific text within a React pre element, but unfortunately, it doesn't seem to be working as expected. Instead of displaying the highlighted text, it shows [object Object]. const Text = styled.pre ` col ...

Merging two distinct arrays of objects in JavaScript can be achieved by utilizing various methods and

I have a challenge where I need to merge two arrays of objects in a nested way. var array1=[{ PersonalID: '11', qusetionNumber: '1', value: 'Something' }, { PersonalID: '12', qusetionNumber: '2& ...

Retrieve the outer-HTML of an element when it is clicked

I am working on a project to develop a tool for locating xpath, and I am seeking the most efficient and user-friendly method for allowing the user to select the desired element on a webpage. Ideally, this selection should be made with just a single click, ...

What causes the white screen issue when utilizing Inertia in Laravel for page rendering?

The technologies I'm working with are: Laravel, Inertiajs, and Vue.js. Although I am new to using Laravel, I encountered an issue when running composer require laravel/breeze --dev and php artisan breeze:install vue which resulted in my Laravel proj ...

Vim users now have access to a powerful PHP debugger specifically designed for debugging command

I recently encountered an issue with my vim debugger that requires me to add an Xdebug cookie in my browser by appending ?XDEBUG_SESSION_START=1. Unfortunately, I found it challenging to set this cookie/session while calling a script on the CLI. Can anyo ...

Utilizing curl to interact with an associative JSON array

I have an array that I need to send: $nums = [ [ 'title' => 'How to build a basic module', 'summary' => 'The summary', 'description' => ...

Locate the specific version of a JavaScript library within compiled JS files

The dist folder houses the results of running npm install. If I don't have access to the original package.json file used during the compilation of the distributable, how can I determine the version of a particular library that was utilized in the ins ...