There are a few things you'll want to do to make you include work and in generally better. Here is the complete code:
function my_theme_enqueue_admin_scripts() {
$screen = get_current_screen(); // This is how we will check what page we are on
if ( in_array( $screen->id, array( 'post', 'page') ) && $screen->action == 'add' ) {
// Use get_template_directory_uri so we don't need to hardcode the URL to our theme folder
wp_enqueue_script('myscript', get_template_directory_uri().'/js/rt_api.js');
}
}
// This action will call your function at the right time to enqueue your script for the admin area
add_action( 'admin_enqueue_scripts', 'my_theme_enqueue_admin_scripts' );
- I used the hook
admin_enqueue_scripts
to call our function to enqueue the script at the correct time for the admin area
- I use the
$screen
object which WordPress creates for the admin area to signal what page is currently being viewed. It has a bunch of attributes on it. In our case, I'm checking $screen->id
for if it is 'post'
or 'page'
, and $screen->action
for if it is 'add'
.
- Finally, I use
get_template_directory_uri()
to get the URL to the theme folder. This way we can use our theme on any WordPress setup without breaking the URL.
Using jQuery in Your Script
When you use jQuery in your scripts, you can't use the $
right off the bat as the version of jQuery included with WordPress disables the $
shorthand for jQuery
. This is because back in the day it is common for multiple Javascript libraries to use $
.
You have two options in your Javascript to use jQuery.
The first is to use jQuery
instead of $
:
jQuery('#my-id').on('click', function() {} );
The second is to wrap the code of your script in a self-calling function. You'll pass jQuery
in as a parameter and then we will name the argument $
:
(function( $ ) {
// your code here
})( jQuery );
Debugging Tips
make sure that your 'myscript' is printed out by viewing the page source
check that the URL printed is correct (it is easy to have a typo)
make sure the Javascript is not without errors
is another script also using the handle myscript
creating a conflict