Unable to sign up for WordPress function

I'm having trouble getting my function registered properly in WordPress, no matter how many times I try.

So far, here's what I've done:

Inserted code into themes functions.php

function test_my_script() {
wp_register_script( 'custom-script', get_template_directory_uri() . '/js/gls-enable.js', array( 'jquery' ) );
wp_enqueue_script( 'custom-script' );
}

add_action( 'wp_enqueue_scripts', 'test_my_script' );

Uploaded my script to the themes folder /js/gls-enable.js

jQuery(document).ready(function($) {
   $("shipping_method_0_flat_rate").change(function () {
    if ($("#shipping_method_0_flat_rate").is(":checked")) {
        window.alert("sometext");
    });
});

Called my script on the page where it needs to run

<?php test_my_script(); ?>

However, upon inspecting the source of the page, the script seems to be missing entirely.

Answer №1

If you want to remove the register_script, here's what you need to do:

function load_custom_script() {
    wp_enqueue_script( 'custom-script', get_template_directory_uri() . '/js/custom.js', array( 'jquery' ) );
}

add_action( 'wp_enqueue_scripts', 'load_custom_script' );

This way, your script will automatically be loaded when the 'wp_enqueue_scripts' hook is triggered, eliminating the need to manually include it in your template using PHP.

Furthermore, there seems to be a mistake in your jQuery code. It should look like this:

jQuery(document).ready(function(){ 
    $("#shipping_method_0_flat_rate").change(function(){ 
        if ( $("#shipping_method_0_flat_rate").is(":checked") ) { 
            window.alert("Text message"); 
        }
    }); 
});

Answer №2

Initially, there is no need to manually call the function test_my_script() on your page. This function is hooked to wp_enqueue_scripts and is automatically loaded by WordPress. Therefore, any errors encountered are likely related to JavaScript.

In this line:

$("shipping_method_0_flat_rate").
, ensure you add a # or . (if it represents an id or class).

The issue may be linked to registering that action in PHP. It would be advisable to set WP_DEBUG to true (located at the root of your WordPress directory, within wp-config.php)

If any errors arise after enabling WP_DEBUG, address them and provide details about the console errors you encounter.

Additionally, it is recommended to load all JavaScript files in the footer (even though the current file loads in the header). There might be a scenario where jQuery is placed in the footer while gls-enable.js loads before it.

To load the script in the footer:

wp_register_script( 'custom-script', get_template_directory_uri() . '/js/gls-enable.js', array( 'jquery' ), '1.0', true );

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

The method jqXHR.abort is not a valid function

I'm currently working on implementing a cancel button for jQuery file upload. Here is the code I have: var jqXHR = $('#fileupload').fileupload({ url: 'server/index.php', dataType: 'json', dropZone: $('#d ...

Tips for navigating a dynamic viewport using scroll movement

Attempting to create a responsive page with two distinct sections at this example link including: Map View Table View Both of these views (table and map divs) need to be responsive without a hard-coded height, so the size of the map div adjusts automatic ...

Guide to Utilizing the Import Function in a Vue 3 Template

Working on a Vue 3 project, my setup includes a stuff.ts file with helpful functions that I need to utilize in my template. <script lang="ts"> import { defineComponent, onMounted } from 'vue' import { doSomething } from ' ...

Tips for achieving compatibility between systemjs module loading and .net mvc architecture

Upon finding the ng-book 2, I saw it as a promising resource to delve into Angular 2. Although I am new to module loaders and have minimal experience with npm and node, I find the terminology and assumed knowledge to be quite perplexing. I decided to use ...

Run PHP script 24 hours after the date of creation

I recently came across an interesting scenario involving webhosting packages. Specifically, I encountered a situation where users could order daily packages that would expire after 24 hours from the creation date. Now, the question arises: How can we ...

Interacting between frames with jQuery

I have main_page.htm with the following frameset structure: <frameset rows="30,*" frameborder=0 border=0> <frame name="top_frame" src="top.htm"> <frame name="bottom_frame" src="bottom.htm"> </frameset> The content in ...

Employ various iterations of the leaflet library

Creating a web application using React and various libraries, I encountered an issue with conflicting versions of the Leaflet library. Currently, I am incorporating the Windy API for weather forecast, which utilizes Leaflet library version 1.4.0. However ...

Uncharted Territory: Exploring asynchronous loops with async await and Promise.race?

Currently, I am involved in a project that requires brute forcing a PDF password. To achieve this task, I am using PDF.js to verify the password and implementing promise.race to execute parallel functions for efficient performance. This is how I have str ...

Sending PHP emails may encounter issues when there is a URL link enclosed in an anchor tag within the email body

There seems to be an issue with sending emails when including an "a href" tag in the mail body. The email sends successfully when the 'a href' and 'www' tags are removed, but this affects the display of other content as per my requirem ...

The state value in React useContext remains unchanged when navigating between pages

Currently, I am delving into the useContext hook and experimenting with a shopping cart exercise in Next.js with app router. This exercise involves managing the cart's value globally. However, I encountered an issue when trying to pass the updated ca ...

The attempt to remove a cookie through a Next.js server-side operation was unsuccessful

Having trouble removing a cookie using the next/headers module in my Next.js application. The code snippet below is what I've tried: import {cookies} from "next/headers"; export default async function Signout() { async function deleteTok ...

PHP is able to fetch an array and then seamlessly transfer it into an object

foreach ($array = $photo_items->fetch_array()) { echo $array['img_src'] . "<br />"; } I am looking to avoid using fetch object in order for this array to be nested within another object. The current output displays 1.jpg2.jpg What ...

Retrieve data from table1 based on the criteria specified in table2

I have a project in mind where users can like each other's photos, and if the feeling is mutual, they become a match. It's similar to the concept of the Tinder app. Currently, I am retrieving one photo using the following query: SELECT id, pict ...

Choose the initial option from a dropdown menu

Is there a way to consistently choose the first item in an HTML select box by index without using val() method? ...

Tips for inserting additional spaces or lines into an XMLWriter PHP fileHere are some suggestions on

Currently, I am utilizing XMLWriter within php to construct a document. However, I am looking to enhance its formatting by inserting additional lines and spaces between elements and components. How can this be achieved? Please refer to the example below: ...

toggle switch for numerical input

Whenever the "Qty" radio button is selected, I need to activate an input box that accepts numbers. Conversely, when the "rate" radio button is clicked, I want to disable this input box. This is how I designed it: <input type="radio" class="radioBtn" ...

Issue with setting a cookie on a separate domain using Express and React

My backend is hosted on a server, such as backend.vercel.app, and my frontend is on another server, like frontend.vercel.app. When a user makes a request to the /login route, I set the cookie using the following code: const setCookie = (req, res, token) = ...

Mastering React hooks: A guide to effectively updating and rendering elements

Each time I click the delete button, it seems to only remove the last element instead of the specific one based on index. Is there a better way to achieve this without changing from <input defaultValue={name} /> to <input value={name} /> in t ...

When attempting to change a Component's name from a string to its Component type in Angular 9, an error is thrown stating that the passed-in type is

When working with Template HTML: <ng-container *ngComponentOutlet="getComponent(item.component); injector: dynamicComponentInjector"> </ng-container> In the .ts file (THIS WORKS) getComponent(component){ return component; //compo ...

Tips for including extra items in a JSON String using Angular 2

function execute(req:any): any { var stReq = JSON.stringify(req); // Adding additional item "Cityname": "angular2City" inside req req.Cityname = 'angular2City'; } Now, how can I include the additional item "Cityname": "angular2C ...