Using WordPress ‘options_discussion_add_js()’ PHP function

The options_discussion_add_js() WordPress PHP function outputs JavaScript to toggle display of additional settings if avatars are disabled.

Usage

options_discussion_add_js();

Parameters

  • None

More information

See WordPress Developer Resources: options_discussion_add_js()

Examples

Toggle Additional Settings for Avatars

To use the options_discussion_add_js() function to display additional settings when avatars are disabled, add the function in your theme’s functions.php file.

function theme_enqueue_scripts() {
  wp_enqueue_script('options-discussion', get_template_directory_uri() . '/js/options-discussion.js', array(), '1.0', true);
}
add_action('wp_enqueue_scripts', 'theme_enqueue_scripts');

In the options-discussion.js file, add the following JavaScript code:

// Toggles the display of additional settings if avatars are disabled
function toggleSettings() {
  var checkbox = document.getElementById("show_avatars");
  var settings = document.getElementsByClassName("avatar-settings");

  if (checkbox.checked) {
    for (var i = 0; i < settings.length; i++) {
      settings[i].style.display = "none";
    }
  } else {
    for (var i = 0; i < settings.length; i++) {
      settings[i].style.display = "block";
    }
  }
}

// Attach event listener to the avatars checkbox
document.getElementById("show_avatars").addEventListener("change", toggleSettings);

// Call the function on page load to set the initial state
toggleSettings();

The code will hide or show additional avatar settings based on the “show_avatars” checkbox state.