How to solve toc.js not working in WordPress

It is common to use toc.js, a JavaScript file, to automatically generate a Table of Contents (TOC) on a WordPress site. However, there are cases where toc.js does not work properly. The main reason for this may be that jQuery is not loaded correctly. This section describes how to solve this problem.

Why is the loading order of jQuery important?

Because toc.js depends on the jQuery library, if jQuery is not loaded first, an error will occur and toc.js will not work properly. jQuery uses the symbols $ andjQuery, so toc.js will not work unless these are available Solution: jQuery is not loading correctly.

Solution: make sure jQuery is loaded.

  1. Open the header.php andfunctions.php files of your WordPress theme and check that jQuery is loaded correctly.
  2. Check the loading order and set it so that jQuery is loaded before toc.js.
  3. To load jQuery, use the wp_enqueue_script function in functions.php. For example, write the following
function enqueue_custom_scripts() {
    wp_enqueue_script('jquery');
    wp_enqueue_script('toc-js', get_template_directory_uri() . '/js/toc.js', array('jquery'), null, true);
}
add_action('wp_enqueue_scripts', 'enqueue_custom_scripts');

This code specifies jQuery as a toc.js dependency, so jQuery is always loaded first.

Troubleshooting: How to check

You can also use the developer tools to check the loading order of jQuery and toc.js. Check for errors in the Console tab and recheck the loading order if you see errors such as jQuery is not defined.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top