2
votes

I've written a simple plugin for my own use and I'm trying to insert some javascript into the head tag.

If I use

add_action( 'init', 'add_to_head' );

Then it works, but it loads before any Jquery does which is no good.

If I use

add_action( 'wp_head', 'add_to_head' );

Then nothing happens at all! This is the function I'm trying to call.

function add_to_head() {?> 
<script>alert("test");</script><?php
}

There's no errors in the console unless I use the add_action 'init' which says Jquery is not defined (obviously).

Update

If I use add_action( 'get_footer', 'add_to_head' ); then it works! But I'm not sure if this is the right hook to use.

2

2 Answers

0
votes

Use wp_footer hook, there is nothing wrong to use wp_footer hook.

<?php
function add_to_head() {?> 
    <script>alert("test");</script><?php
}
add_action( 'wp_footer', 'add_to_head' );
?>
0
votes

Try to give priority so that your code will add before

function mycustom_enqueue() {     
    echo "<script type='text/javascript'>alert('1');</script>";
}
add_action( 'wp_head', 'mycustom_enqueue',100 );
//here 100 is prioriry