I try this:
add_action('admin_print_scripts', 'custom_admin_scripts' );
function custom_admin_scripts() {
echo '<script type="text/javascript" src="' . get_bloginfo('stylesheet_directory') . /admin-scripts.js"></script>';
}
but by this way it doesn’t recognize jQuery. So I get Uncaught ReferenceError: jQuery is not defined
.
I think that it because jQuery is linked after my script. As I see in HTML source:
<script type="text/javascript" src="http://localhost:8080/wp-test/wp-content/themes/test/admin-scripts.js"></script>
<script type="text/javascript" src="http://localhost:8080/wp-test/wp-admin/load-scripts.php?c=1&load=jquery,utils&ver=edec3fab0cb6297ea474806db1895fa7"></script>
How can I fix it?
The problem is that you are loading your script before jQuery has been loaded.
Do not print scripts directly.
You should (register and then) enqueue them using the provided API. jQuery is already a registered script, so you can just enqueue it (say on the
admin_enqueue_scripts
hook).However you only need to load jQuery if you are loading a custom script that requires it, in which case you should enqueue your custom script and add jQuery as a dependency. WordPress will then handle the loading of the scripts and in the correct order:
Side remarks
get_template_directory_uri()
rather thanget_bloginfo()
$hook
(which will beedit.php
,post.php
,post-new.php
etc) andget_current_screen()
to determine if you are on a page that requires your script to be loaded. Only load scripts when you actually need them.E.g (Codex example):
First, let’s include them in a proper way.
Second, take a read here http://wpcandy.com/teaches/how-to-load-scripts-in-wordpress-themes