skip to Main Content

I get really annoyed that the block/part that is usually set for adding custom JS in WordPress themes, is very small and not convenient to write in.

Searching for a way to add a bigger code, without child theme, in a way that it won’t be over-written after update, and more convenient than the small box in: Customize -> General -> Custom CSS&JS.

2

Answers


  1. Chosen as BEST ANSWER

    Finally I used Code Snippets plugin, but when using their example to add js, it loads the code in the beginning before the document has been loaded. This way, I couldn't edit the existing page/style/blocks/tags.

    It's not very complicated but here's the small addition:

    // ensure that query has been loaded to use: jQuery / $()
    add_action( 'wp_enqueue_script', function () {
        wp_enqueue_script( 'jquery' );
    } );
    
    // add your custom function
    add_action( 'wp_head','my_custom_function'); 
    
    function my_custom_function() { 
    ?>
    
    <script>
    
      jQuery(document).ready(function() {
        // ...
        // write your custom javascript code here
        // ...
      }
    
    </script>
    <?php }
    

  2. In file you are writing code must be called right before body tag and after your html code. Still if you want to use in same file then use below code with setTimeout.

        // ensure that query has been loaded to use: jQuery / $()
    add_action( 'wp_enqueue_script', function () {
        wp_enqueue_script( 'jquery' );
    } );
    
    // add your custom function
    add_action( 'wp_head','my_custom_function'); 
    
    function my_custom_function() { 
    ?>
    
    <script>
    
      jQuery(document).ready(function() {
        setTimeout(function(){
            // ...
            // write your custom javascript code here
            // ...
        },1000);
      }
    
    </script>
    <?php }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search