Using WordPress ‘options_general_add_js()’ PHP function

The options_general_add_js() WordPress PHP function is used to display JavaScript on a page.

Usage

To use the options_general_add_js() function, simply call the function and add your JavaScript code as a string.

options_general_add_js("alert('Hello, World!');");

Parameters

This function has no parameters.

More information

See WordPress Developer Resources: options_general_add_js

This function is not part of the official WordPress core and may not be available in all installations.

Examples

Display an alert box

This example uses the options_general_add_js() function to display a simple alert box.

// Display an alert box with a message
options_general_add_js("alert('This is an alert box');");

Redirect user to another page

This example demonstrates how to use the function to redirect users to another page.

// Redirect user to example.com
options_general_add_js("window.location.href='https://example.com';");

Change background color of an element

This example shows how to change the background color of an element with the ID ‘myElement’.

// Change the background color of an element with ID 'myElement' to red
options_general_add_js("document.getElementById('myElement').style.backgroundColor='red';");

Hide an element

This example demonstrates how to hide an element with the ID ‘hideMe’ using the options_general_add_js() function.

// Hide an element with ID 'hideMe'
options_general_add_js("document.getElementById('hideMe').style.display='none';");

Add a click event listener to a button

This example shows how to use the function to add a click event listener to a button with the ID ‘myButton’.

// Add a click event listener to a button with ID 'myButton'
options_general_add_js("document.getElementById('myButton').addEventListener('click', function() { alert('Button clicked!'); });");