Enqueue Javascript Correctly for 3.5

I am trying to create tabs for admin settings page in wp, but I think I’m doing it wrong. The example below shows how I did it but I don’t know how to change this to use it correctly with no conflict ie. $.

function my_plugin_load_js() {
wp_deregister_script('jquery');
wp_register_script('jquery', 'http://code.jquery.com/jquery-1.8.3.js');
wp_enqueue_script('jquery');

wp_deregister_script('jquery-ui-core');
wp_register_script('jquery-ui-core', 'http://code.jquery.com/ui/1.9.2/jquery-ui.js');
wp_enqueue_script('jquery-ui-core');
}
add_action('admin_enqueue_scripts', 'my_plugin_load_js' );

function mypluginjs() {
echo '<script type="text/javascript">
jQuery(function() {
   jQuery( "#tabs" ).tabs();
});
</script>';
}
add_action( 'admin_print_scripts', 'mypluginjs' );

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Never de-register core-bundled scripts in the WP-Admin. You shouldn’t do it on the front end, either, unless you really, really know what you’re doing. But especially in the WP-Admin, just use the core-bundled scripts.

Also, when you use core-bundled jQuery UI, WordPress already knows that jQuery is a dependency.

Just change the first callback to this:

function my_plugin_load_js() {
    wp_enqueue_script('jquery-ui-core');
}
add_action('admin_enqueue_scripts', 'my_plugin_load_js' );

Note: you should be using a plugin-specific hook here, to enqueue only on your own Plugin’s admin page, rather than enqueueing in the entire WP-Admin.

Also, for jQuery UI Tabs, you’ll need to enqueue the jquery-ui-tabs script. Core registers it with all its needed deps, so you can just enqueue it directly:

function my_plugin_load_js() {
    wp_enqueue_script('jquery-ui-tabs');
}
add_action('admin_enqueue_scripts', 'my_plugin_load_js' );

For the second, just properly wrap the script in no-conflict wrappers:

function mypluginjs() {
    ?>
<script type="text/javascript">
jQuery(document).ready(function($) {
   jQuery( "#tabs" ).tabs();
});
</script>
    <?php
}
add_action( 'admin_print_scripts', 'mypluginjs' );


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x